c++ - 使用 std::vector 在类中分配索引

标签 c++ class vector operator-overloading stdvector

我有一个像这样初始化的 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/

相关文章:

c# - 在两个命名空间中使用相同的类名 - 优先考虑其中之一

class - 如何在 AutoHotkey 中创建一个类?

c++ - 如何从多个 vector 中删除相同的行位置?

C++ 错误 : vector subscript out of range, 行 1201

c++ - 在cuda内核中创建一个 vector

c++ - 不理解通过函数传递的 C++ 参数

c++ - 将 char 数组传递给 C++ 中的函数时的不同行为

javascript - JS - 从同一类中的其他方法调用类中的方法

c++ - 试图从 Derived* 的 vector 中分配 Base* 的 vector

c++ - Visual Studio C++ 无法从另一个目录中找到头文件