我有这个例子来生成唯一的对象到一个 vector 中:
#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);
}
如果我把 main 改成这个:
struct B
{
B( const int n) : v(n)
{
}
std::vector< A > v;
};
然后将一个类型A的对象复制到所有vector元素中。
有没有办法创建一个包含所有唯一对象的 vector (如第一个示例中所示)?
为了更清楚:我有一个包含 vector 的类。此 vector 必须包含所有唯一对象(不是一个对象的拷贝)。我想在初始化列表中初始化它(而不是在构造函数的主体中)。
最佳答案
您的第一次尝试是有效的。
在当前标准C++03中这一行
std::vector< A > as( n );
明确定义为创建一个 A
对象并复制该 n
次。
我相信在 C++0x 中,这被更改为创建 n
默认构造的 A
(一个小差异)。然后,您也许可以在 A
的构造函数中做一些事情,使每个实例都是唯一的。
现在你不能。
关于c++ - 如何生成具有唯一值的 vector ?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6855293/