简体   繁体   中英

vector as a Data Member in C++

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!

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

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;
};

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) { /* ... */ }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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