Initialize a Vector in C++ With Examples

In this article, we’ll take a look at some of the ways to initialize a vector in C++. There are a bunch of ways to do this, so we’ll go through each approach.

Let’s get started!


Method 1: (Recommended): Use an Initializer List (C++11 and above)

If your compiler supports the C++ version above C++11, you can simply initialize the vector using the {} notation.

Since std::vector is a class, to initialize an object of this class using the above fashion, this refers to an Initializer List in C++.

Here is an example using the initializer list declaration:

Since initializer lists were introduced only in C++11, you need a minimum compiler version supporting at least C++11 to use this method.

Here is an example program to demonstrate this type of initialization:

Here, we use a range-based for-loop to print the vector elements.

Output

Method 2: Initialize a Vector in C++ with the help of an array (C++0x)

If you’re using a C++0x (C++03, C++07, etc) based compiler, you can still achieve the initialization using arrays.

Test this on a C++0x based compiler, to verify that it works.

If you’re on Linux (g++ based compiler), compile and run using:

Output

Method 3: Using the <boost> library (C++11 and above)

We can also use the <boost> library to achieve this.

The <boost/assign> namespace has the list_of construct to initialize vectors.

We can also use the overloaded + operator to declare a vector and add elements.

However, this type of operator overloading is not advisable, as it can be confusing for many readers, as a person reading this code may also think that the first element will add to 1, the second element adding to 2, etc.


Conclusion

In this article, we learned how we could initialize a vector in the C++ language in different ways.


References


By admin

Leave a Reply