I want to make a vector first without a size ( vector<int> times
) and I want to define its size later in a constructor of a class ( times(size)
).
I can do it by using the initializer list as you see below
class A (int size): times(size) {};
But my question is that why I can not do it in a constructor out of a class like the code below?
I mean why the code below is wrong?
class A
{
public:
A(int size);
private:
std::vector<int> line;
};
A::A(int size)
{
line(size);// here I got the error
}
line(size)
make an error
Another way to initialize a vector in C++ is to pass an array of elements to the vector class constructor. The array elements will be inserted into the vector in the same order, and the size of the vector will be adjusted automatically. You pass the array of elements to the vector at the time of initialization.
We can set the size of a Vector using setSize() method of Vector class. If new size is greater than the current size then all the elements after current size index have null values. If new size is less than current size then the elements after current size index have been deleted from the Vector.
vector::size() size() function is used to return the size of the vector container or the number of elements in the vector container.
To get the size of a C++ Vector, you can use size() function on the vector. size() function returns the number of elements in the vector.
You can use the member function std::vector::resize
for that
A::A(int size)
{
line.resize(size);
}
The member line
will be default constructed(i.e. std::vector<int> line{}
) before reaching the body of the constructor. And hence writing line(size);
makes no sense, hence
the compiler error.
Much better would be using the member initializer lists, which will help
to construct the vector from the size passed and initialize with 0
's, before reaching the constructor body.
A(int size) : line(size) {}
It uses the following constructor of std::vector
explicit vector( size_type count ); // (since C++11)(until C++14)
explicit vector( size_type count, const Allocator& alloc = Allocator() ); // (since C++14)
You probably want to either use an initializer list:
A::A(int size) : line(size)
{ }
or assign a new value to line
:
A::A(int size)
{
this->line = std::vector(size);
}
These two options will insert size
elements into the vector. So the vector will be filled with default values. If you only want to make sure there is enough space to insert that many elements on a later point in time use reserve to increase capacity of the already constructed vector:
A::A(int size)
{
this->line.reserve(size);
}
If you use the first or second option line.size()
and line.capacity()
will be equal size
, because default elements have been inserted into the vector.
With the third option, no default elements will be inserted, so line.size()
will be 0 and line.capacity()
is size
.
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