vector作为C ++中的数据成员

时间:2013-12-30 23:46:59

标签: c++ vector

在C ++中,如何在我的班级中包含101个元素向量作为数据成员?我正在做以下事情,但它似乎没有起作用:

private:
    std::vector< bool > integers( 101 );

我已经包含了矢量标头。提前致谢!

3 个答案:

答案 0 :(得分:12)

class myClass {
    std::vector<bool> integers;
public:
    myClass()
        : integers(101)
    {}
};

我也喜欢std::array的想法。如果你真的不需要这个容器在运行时改变它的大小,我会建议使用固定大小的数组选项

答案 1 :(得分:9)

如果您知道自己只需要101个元素,请使用std::array

class A
{
    //...
private:
    std::array<bool, 101> m_data;
};

如果您可能需要更多,并且您只想为其指定默认大小,请使用初始化列表:

class A
{
public:
    A() : m_data(101) {} // uses the size constructor for std::vector<bool>
private:
    std::vector<bool> m_data;
};

答案 2 :(得分:5)

您无法使用常规构造语法在类定义中构造对象。但是,您可以使用统一初始化语法:

#include <vector>
class C {
    std::vector<bool> integers{ 101 };
};

如果你需要使用C ++ 03,你必须从成员初始化列表构造你的向量:

C::C(): integers(101) { /* ... */ }