vector as a Data Member in C++

2019-02-23 06:55发布

问题:

In C++, how do I include a 101 elements vector as a data member in my class? 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!

回答1:

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

I also like the std::array idea. 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



回答2:

If you know you will only ever need 101 elements, use 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;
};


回答3:

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::C(): integers(101) { /* ... */ }


标签: c++ vector