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!
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()
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.
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
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.
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) { /* ... */ }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With