Initialization of Vector in C++

New to C++ vectors? This guide provides a clear, overview of the various methods for the Initialization of Vector in C++, including 2D vectors. With commented code, outputs, and “Try it yourself” challenges, you’ll learn how to set up vectors for any use case, from simple lists to complex grids, in a way that is easy to understand and apply.

🔹 What is Vector Initialization?

Initialization of Vector in C++ refers to the process of creating a vector and giving it its initial set of values. Choosing the right method is crucial for writing clean, efficient, and readable code. Modern C++ provides multiple flexible ways to do this, catering to different needs, from creating an empty vector to populating it with data from other sources.

🔹 Method 1: Default Constructor (Empty Vector)

The simplest way to create a vector is to declare it without any initial values. This creates an empty vector with a size of 0, to which you can add elements later.

#include <iostream>
#include <vector>
using namespace std;
int main() {
    vector<int> myVector;
    cout << "Initial size: " << myVector.size() << endl;
    myVector.push_back(10);
    myVector.push_back(20);
    cout << "Size after adding elements: " << myVector.size() << endl;
    cout << "First element: " << myVector[0] << endl;
}

Output

Initial size: 0
Size after adding elements: 2
First element: 10

Try it yourself

  • Create an empty vector of strings and add three names to it.
  • Check if the vector is empty using the .empty() method before and after adding elements.

🔹 Method 2: Initializer List (C++11 and later)

The most common and readable method for the Initialization of Vector in C++ is using an initializer list (curly braces {}). This lets you specify the initial elements directly.

#include <iostream>
#include <vector>
#include <string>
using namespace std;
int main() {
    vector<int> numbers = {10, 20, 30, 40, 50};
    vector<string> fruits = {"Apple", "Banana", "Cherry"};
    cout << "First number: " << numbers[0] << endl;
    cout << "Second fruit: " << fruits[1] << endl;
}

Output

First number: 10
Second fruit: Banana

Try it yourself

  • Create a vector of doubles with three decimal values.
  • Initialize a vector with a single element using this method.

🔹 Method 3: Fill Constructor (Size and Value)

To create a vector of a specific size where all elements are the same, use the fill constructor. This is highly efficient for pre-allocating and setting a default value.

#include <iostream>
#include <vector>
using namespace std;
int main() {
    vector<int> scores(5, 100);
    cout << "Vector elements: ";
    for (int score : scores) {
        cout << score << " ";
    }
    cout << endl;
    vector<bool> flags(4, false);
    cout << "First flag: " << boolalpha << flags[0] << endl;
}

Output

Vector elements: 100 100 100 100 100
First flag: false

Try it yourself

  • Create a vector of 10 characters, all initialized to ‘X’.
  • Try vector<int> v(5); without a second argument and print its contents.

🔹 Method 4: Copy Constructor (From Another Vector)

You can initialize a vector as a complete copy of another existing vector. This creates a new, independent vector with the same elements.

#include <iostream>
#include <vector>
using namespace std;
int main() {
    vector<int> original = {1, 2, 3};
    vector<int> copy1(original);
    vector<int> copy2 = original;
    cout << "Copy 1, first element: " << copy1[0] << endl;
    cout << "Copy 2, second element: " << copy2[1] << endl;
    copy1[0] = 99;
    cout << "Original's first element after modification: " << original[0] << endl;
    cout << "Copy 1's first element: " << copy1[0] << endl;
}

Output

Copy 1, first element: 1
Copy 2, second element: 2
Original's first element after modification: 1
Copy 1's first element: 99

Try it yourself

  • Create a vector and initialize a second vector with only the first half of the elements from the original using iterators.

🔹 Method 5: From an Array or Other Iterators

You can initialize a vector from any range specified by two iterators. This makes it easy to populate a vector from a C-style array or another container like a std::list or std::deque.

#include <iostream>
#include <vector>
#include <iterator>
using namespace std;
int main() {
    int classicArray[] = {5, 10, 15, 20};
    vector<int> fromArray(begin(classicArray), end(classicArray));
    cout << "Vector from array: ";
    for (int val : fromArray) {
        cout << val << " ";
    }
    cout << endl;
}

Output

Vector from array: 5 10 15 20

Try it yourself

  • Create a std::list<int> and initialize a vector from it.
  • Initialize a vector from a sub-section of an array (e.g., second to fourth element).

🔹 Method 6: Using `std::fill` or `std::generate`

For more complex initialization patterns, you can first create a vector of a certain size and then use algorithms like std::fill or std::generate to populate it.

#include <iostream>
#include <vector>
#include <algorithm>
#include <numeric>
using namespace std;
int main() {
    vector<int> filledVector(5);
    fill(filledVector.begin(), filledVector.end(), 8);
    cout << "Filled vector: ";
    for (int val : filledVector) cout << val << " ";
    cout << endl;
    vector<int> sequence(5);
    iota(sequence.begin(), sequence.end(), 1);
    cout << "Sequence vector: ";
    for (int val : sequence) cout << val << " ";
    cout << endl;
}

Output

Filled vector: 8 8 8 8 8
Sequence vector: 1 2 3 4 5

Try it yourself

  • Use std::generate with a lambda function to fill a vector with random numbers.

🔹 Initialization of 2D Vector in C++

Initializing a 2D Vector in C++ follows the same principles, just applied to a vector of vectors. Here are the most common methods, including initialization from a 2D C-style array.

#include <iostream>
#include <vector>
using namespace std;
void printGrid(const vector<vector<int>>& grid) {
    for (const auto& row : grid) {
        for (int cell : row) cout << cell << " ";
        cout << endl;
    }
    cout << "------------------" << endl;
}
int main() {
    int rows = 3, cols = 4;
    vector<vector<int>> uniformGrid(rows, vector<int>(cols, -1));
    cout << "3x4 Grid of -1s:" << endl;
    printGrid(uniformGrid);
    vector<vector<int>> jaggedGrid = {{1,0,0},{0,1,0},{0,0,1}};
    cout << "Identity Matrix from Initializer List:" << endl;
    printGrid(jaggedGrid);
    int C_array[2][3] = {{10,20,30},{40,50,60}};
    vector<vector<int>> gridFromArray;
    for (const auto& row_array : C_array)
        gridFromArray.push_back(vector<int>(begin(row_array), end(row_array)));
    cout << "Grid From 2D C-Array:" << endl;
    printGrid(gridFromArray);
}

Output

3x4 Grid of -1s:
-1 -1 -1 -1
-1 -1 -1 -1
-1 -1 -1 -1
------------------
Identity Matrix from Initializer List:
1 0 0
0 1 0
0 0 1
------------------
Grid From 2D C-Array:
10 20 30
40 50 60
------------------

Try it yourself

  • Create a 5×5 2D vector where every element is 7.
  • Build a 2D vector row by row using a loop and push_back().

🔹 FAQ: Initialization of Vector in C++

Q1. What is the most common way to initialize a vector?
For C++11 and newer, using an initializer list (e.g., vector<int> v = {1, 2, 3};) is the most common, readable, and preferred method for hardcoded values.

Q2. How do I initialize a vector with a user-defined size?
Use the fill constructor: vector<int> v(size, defaultValue);. For example, to get the size from user input, you could write cin >> n; vector<int> myVector(n, 0);.

Q3. What is the difference between () and {} for initialization?
Parentheses () typically call a constructor, often for size-based initialization (e.g., `vector(5, 1)`). Curly braces `{}` are for initializer-list initialization (e.g., `vector{5, 1}`). Be careful: `vector v(5)` creates a vector of 5 zeros, while `vector v{5}` creates a vector with one element, 5.

Q4. How do I initialize a const vector?
You must initialize a const vector at the moment of its declaration, as it cannot be changed later. For example: const vector<string> DAYS = {"Mon", "Tue", "Wed"};.

Q5. What is the most efficient way to initialize a large vector?
If you know the size beforehand, using the fill constructor vector<T>(size, value) is very efficient. If you are adding elements one by one, calling .reserve(size) before a loop of .push_back() calls can prevent reallocations and improve performance.

🔹 Wrapping Up

Mastering the different methods for the Initialization of Vector in C++ allows you to write more expressive, efficient, and appropriate code for any situation. Whether you’re creating a simple list of items, a large pre-filled buffer, or a complex 2D grid, there is a clear and idiomatic way to get started. Practice the “Try it yourself” challenges to solidify your understanding and make these techniques second nature.

Leave a Comment

About RadiantRiva

Your go-to resource for coding tutorials, developer guides, and programming tips.

Learn More

Quick Links

Follow Us

Newsletter

Get coding tips, tutorials, and updates straight to your inbox.