Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

vector as a Data Member in C++

Tags:

c++

vector

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!

like image 837
Fernando Karpinski Avatar asked Dec 30 '13 23:12

Fernando Karpinski


People also ask

What is vector_name data in C++?

vector data() function in C++ STL. The std::vector::data() is an STL in C++ which returns a direct pointer to the memory array used internally by the vector to store its owned elements. Syntax: vector_name data()

How do you know if a vector is const qualified?

If the vector object is const-qualified, the function returns a pointer to const value_type. Otherwise, it returns a pointer to value_type. Member type value_type is the type of the elements in the container, defined in vector as an alias of the first class template parameter ( T ). Constant.

How do you access a vector element from another variable?

Accessing Vector Elements Using Another Pointer Variable We can initialize a pointer of appropriate type so as to point to any element of a vector and then manipulate the vector elements using this pointer. Thus, if a is an integer vector and pa is an integer pointer, we can initialize pointer pa to point to the ith element of vector as 1

How does a pointer step through a vector in C++?

However, as the loop progresses, the pointer is made to step through the vector elements by using the pointer-increment operation. As the pointer always points to the vector element to be processed, the value of the current element is obtained by dereferencing the pointer, as *pa.


3 Answers

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

like image 81
smac89 Avatar answered Sep 21 '22 07:09

smac89


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;
};
like image 32
Zac Howland Avatar answered Sep 21 '22 07:09

Zac Howland


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) { /* ... */ }
like image 33
Dietmar Kühl Avatar answered Sep 19 '22 07:09

Dietmar Kühl