Open In App

Initialize a Vector with Hardcoded Elements

Last Updated : 05 Dec, 2024
Comments
Improve
Suggest changes
Like Article
Like
Report

C++ allows us to initialize the vector with hardcoded (predefined) elements. In this article, we will learn how to initialize the vector with predefined elements.

The simplest method to initialize the vector with hardcoded elements is to use an initializer list where we specify the values inside curly braces {}.

C++
#include <bits/stdc++.h>
using namespace std;

int main() {

    // Initialize vector with hardcoded elements
    vector<int> v = {1, 3, 7, 9};

    for (auto i : v)
        cout << i << " ";
    return 0;
}

Output
1 3 7 9 

Explanation: Here, the initializer list {1, 3, 7, 9} defines the elements of the vector. This method is concise and efficient, especially for initializing small vectors.

Apart from above method, vector assign() can also be used to initialize the vector with predefined values. In this method we have to pass the hardcoded elements as an initializer list inside the assign() function.

C++
#include <bits/stdc++.h>
using namespace std;

int main() {
    vector<int> v;

    // Initialize vector with hardcoded elements
    v.assign({1, 3, 7, 9});

    for (auto i : v)
        cout << i << " ";
    return 0;
}

Output
1 3 7 9 

Explanation: In this method, the assign() function populate the vector with values written in the program. This is useful when reinitializing an already existing vector.


Next Article
Article Tags :
Practice Tags :

Similar Reads