vector as a Data Member in C++

后端 未结 3 1005
孤城傲影
孤城傲影 2021-01-13 04:21

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::         


        
相关标签:
3条回答
  • 2021-01-13 04:36
    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

    0 讨论(0)
  • 2021-01-13 04:41

    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) { /* ... */ }
    
    0 讨论(0)
  • 2021-01-13 04:52

    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;
    };
    
    0 讨论(0)
提交回复
热议问题