Initialize Vector with Initializer List in C++

A very popular and common way to Initialize a Vector nowadays is through the use of a C++ Initializer List.

Initializers Lists are actually used to initialize all manner of containers and variables, and are used in Arrays and Classes. The syntax is pretty straightforward, which is simply to use curly brackets enclosing the value(s) you wish to insert into the vector.

Note that Initializer lists is a feature introduced in C++11, so if your C++ version is not up to date, it might not be supported.


Using the Initializer List

The below example shows how we can use the C++ Initializer List to store three integers into a vector. The three integers will be added into the vector in the same order as they are in the initializer list.

vector<int> vec { 10, 20, 30 };

As Vectors are dynamic, unlike Arrays, we don’t need to specify a size for the vector when using the Initializer List. The vector will automatically grow as values from the Initializer list are added to it.

An alternate way of writing the above code is using an = operator between the name and the initializer list.

vector<int> vec = { 10, 20, 30 };

Initializing 2D Vectors with Initializer list

Initializer lists are not limited to just normal Vectors, and can be used to initialize multi-dimensional vectors as well. All you have to do is nest initializer lists within each other as shown below.

vector<vector<int> > vec { { 1, 1, 1 },
                           { 2, 2, 2 },
                           { 3, 3, 3 } };

The number of nested curly-bracket pairs decides how many vectors are inserted into the 2D Vector. In the case of the above image, there are 3 pairs of curly-brackets. This creates a 2D Vector, with three Vectors in it, initialized to { 1, 1, 1 }, { 2, 2, 2 } and { 3, 3, 3 } respectively.

Another rather interesting thing to keep in mind, is that as Vectors are dynamic, the 1D Vectors within the 2D Vector can be of different sizes! We can initialize them with initializer lists of different sizes, as shown below.

#include <iostream>
#include <vector>
using namespace std;

int main() {
    vector<vector<int> > vec { { 1, 2, 3, 4 },
                               { 5, 6 },
                               { 7, 8, 9 } };

    for (int i = 0; i < vec.size(); i++) {
        for (int j = 0; j < vec[i].size(); j++) {
            cout << vec[i][j] << " ";
        }
        cout << endl;
    }
}
1 2 3 4
5 6
7 8 9

Of course, you aren’t limited to just 2D vectors. You can make this work for 3D and 4D vectors as well, if you simply nest more initializer lists within each other.


This marks the end of the Initialize Vector with Initializer List in C++ Tutorial. Any suggestions or contributions are more than welcome. Questions regarding the tutorial content can be asked in the comments section below.

Subscribe
Notify of
guest
0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments