我有一个像这样初始化的 30 个实例的 std::vector:
#include <vector>
class Foo {
public:
int x;
int Index; // I want this to be initialized when std::vector start the
// Instances.
Foo(int& _x) : x(_x) {}
int Function(){
// Do something cool ...
}
};
int main(){
int a = 5;
std::vector<Foo> Instances (30, a);
return 0;
}
所以当我调用 std::vector<Foo> Instances (30, SomeVariablePassedByReference);
时我想要那个每个成员变量 Index
每个 Instance 得到相应的数字(0-30)。
我怎样才能做到这一点?也许使用运算符重载?我不想使用 C-Stylish [ ] 运算符。
最佳答案
你想让 Foo 的一个成员变量成为 vector 中的索引?只需为每个成员调用 ctor 并将其插入 vector 。
#include <vector>
class Foo {
public:
int a;
int Index; // I want this to be initialized when std::vector start the
// Instances.
Foo(int _index, int& _x) : Index(_index), a(_x) {}
void func(){
// Do something cool ...
}
};
int main(){
int a = 5;
std::vector<Foo> Instances;
Instances.reserve(30);
for(size_t i=0;i<30;i++)
Instances.emplace_back(i,a);
return 0;
}
关于c++ - 使用 std::vector 在类中分配索引,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52377286/