如何生成具有唯一值的向量?

BЈо*_*вић 7 c++ vector initialization-list

我有这个例子来生成一个向量中的唯一对象:

#include <iostream>
#include <vector>
#include <algorithm>

int v=0;

struct A
{
    A() : refValue( v++)
    { std::cout<<"constructor refValue="<<refValue<<std::endl; }
    A( const A &r ) : refValue(r.refValue)
    { std::cout<<"copy constructor refValue="<<refValue<<std::endl; }
    A& operator=( const A &r )
    {
        refValue = r.refValue;
        std::cout<<"operator= refValue="<<refValue<<std::endl;
        return *this;
    }
    ~A() { std::cout<<"destructor refValue="<<refValue<<std::endl; }

    int refValue;
};

A GenerateUnique()
{
    A unique;
    return unique;
}
struct B
{
    B( const int n) : v()
    {
        std::generate_n( std::back_inserter( v ), n, &GenerateUnique );
    }
    std::vector< A > v;
};

int main()
{
    B b(3);
}
Run Code Online (Sandbox Code Playgroud)

如果我将主要内容改为:

struct B
{
    B( const int n) : v(n)
    {
    }
    std::vector< A > v;
};
Run Code Online (Sandbox Code Playgroud)

然后将一个A类型的对象复制到所有向量元素中.

有没有办法创建一个包含所有唯一对象的向量(如第一个示例中所示)?

为了更清楚:我有一个包含向量的类.此向量必须包含所有唯一对象(不是一个对象的副本).我想在初始化列表中初始化它(不在构造函数的主体中).

unk*_*ulu 3

它被复制,因为构造函数的签名如下:

\n\n
\xe2\x80\x8bexplicit vector( size_type count,\n             const T& value = T(),\n             const Allocator& alloc = Allocator());\n
Run Code Online (Sandbox Code Playgroud)\n\n

很明显,您只需将默认构造的对象传递给此构造函数,它就会复制它。

\n\n

如果您想在初始化列表中进行初始化,显然您只能使用某些对象的构造函数。我想,您不想创建一个包装类只是为了初始化初始化列表中的向量,所以我们仅限于向量的构造函数。唯一看起来合理的是

\n\n
template <class InputIterator>\n\nvector( InputIterator first, InputIterator last,\n        const Allocator& alloc = Allocator() );\n
Run Code Online (Sandbox Code Playgroud)\n\n

因此,您可以创建一个迭代器来返回所需数量的默认构造对象。

\n\n

不过,我建议只在构造函数主体中进行构造。

\n