Initialize a vector in C++
This post will discuss how to initialize a vector in C++.
There are several ways to initialize a vector in C++, as shown below:
1. Using Initializer List
In C++11 and above, we can use the initializer lists '{...}' to initialize a vector. This won’t work in C++98 as standard allows the vector to be initialized by a constructor and not by '{...}'.
|
1 2 3 4 5 6 7 8 9 10 11 12 13 |
#include <iostream> #include <vector> int main() { std::vector<int> vec { 1, 2, 3, 4, 5 }; for (int i: vec) { std::cout << i << ' '; } return 0; } |
Output:
1 2 3 4 5
2. Using Copy Constructor
We can use a copy constructor to initialize the vector from another vector elements, following the same order of elements.
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 |
#include <iostream> #include <vector> int main() { std::vector<int> v = { 1, 2, 3, 4, 5 }; // copy constructor std::vector<int> vec(v); for (int i: vec) { std::cout << i << ' '; } return 0; } |
Output:
1 2 3 4 5
3. Using Range Constructor
We can use a range constructor to initialize vectors from elements of an array or another container.
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 |
#include <iostream> #include <vector> int main() { int arr[] = { 1, 2, 3, 4, 5 }; std::vector<int> vec(std::begin(arr), std::end(arr)); // or do initialize like this // std::vector<int> vec(arr, arr + sizeof(arr)/sizeof(int)); for (int i: vec) { std::cout << i << ' '; } return 0; } |
Output:
1 2 3 4 5
4. Using Fill Constructor
We can use a fill constructor to initialize a vector of specified size by specified element.
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 |
#include <iostream> #include <vector> int main() { int val = 1; unsigned int n = 5; // fill constructor std::vector<int> vec(n, val); for (int i: vec) { std::cout << i << ' '; } return 0; } |
Output:
1 1 1 1 1
5. Using Default Constructor
Finally, we can use the empty container constructor (or a default constructor) to construct an empty vector (with no elements), as shown below:
|
1 2 3 4 5 6 7 8 9 10 11 12 13 |
#include <iostream> #include <vector> int main() { std::vector<int> vec; for (int i: vec) { std::cout << i << ' '; } return 0; } |
That’s all about initializing a vector in C++.
Thanks for reading.
To share your code in the comments, please use our online compiler that supports C, C++, Java, Python, JavaScript, C#, PHP, and many more popular programming languages.
Like us? Refer us to your friends and support our growth. Happy coding :)