How does vector initialize and allocate in one line?

How, as vector<int> n(9) is allocating, can vector initialize and allocate in one line (as giving error in this e.g.) ?
1
2
3
4
5
6
7
8
9
10
11
12
#include <vector>
using namespace std;



int main(){

int *k;

vector<int> l(9){1,2,3};

// cout << l[0] <<endl; 
Last edited on
The statement
vector<int> l(9);
Declares a vector with size 9, and
vector<int> l{1, 2, 3};
Declares a vector with size 3.
What should the size of this be?
vector<int> l(9){1,2,3};

In any event you can do complicated initialization within an anonymous function, called immediately:
auto l = [&]{ std::vector<int> v{ 1, 2, 3 }; v.resize(9); return v; }();
Last edited on
The wording of your title implies you're asking "How does [thing that exists] work?".

can vector initialize and allocate in one line
No (unless you cheat and put multiple statements on the same line).
It's either is the constructor that takes in a size, or the constructor that takes in a std::initializer_list.
Last edited on
Note that the number that you pass to the constructor (inside the parentheses) specifies the size of the vector (i.e. the number of elements), not the capacity (i.e. how many elements the vector has allocated space for).

If you want a vector of size 9 where the first three elements have values 1, 2 and 3 and the rest have value 0 then you can do it in one statement as:
 
std::vector<int> l{1, 2, 3, 0, 0, 0, 0, 0, 0};

Or you could use resize as mbozzi suggested, but there is no need to use a lambda.
1
2
std::vector<int> l{1, 2, 3};
l.resize(9);

If you want a different value than zero you can pass it as a second argument to resize.
 
l.resize(9, 5); // new elements will get the value 5 

Last edited on
Topic archived. No new replies allowed.