简体   繁体   English

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

[英]vector as a Data Member in C++

In C++, how do I include a 101 elements vector as a data member in my class? 在C ++中,如何在我的类中包含101元素向量作为数据成员? I'm doing the following, but it doesn't seem to be working: 我正在做以下事情,但似乎没有起作用:

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

I already included the vector header. 我已经包含了矢量标题。 Thanks in advance! 提前致谢!

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

I also like the std::array idea. 我也喜欢std::array想法。 If you really don't need this container to change it's size at run-time, I will suggest going with the the fixed size array option 如果你真的不需要这个容器在运行时改变它的大小,我会建议使用固定大小的数组选项

If you know you will only ever need 101 elements, use std::array : 如果您知道只需要101个元素,请使用std::array

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

If you might need more and you just want to give it a default size, use an initializer list: 如果您可能需要更多,并且您只想为其指定默认大小,请使用初始化列表:

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

You can't use the normal construction syntax to construct an object in the class definition. 您不能使用常规构造语法在类定义中构造对象。 However, you can use uniform initialization syntax: 但是,您可以使用统一初始化语法:

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

If you need to use C++03, you have to constructor your vector from a member initializer list instead: 如果你需要使用C ++ 03,你必须从成员初始化列表构造你的向量:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM