Create Vector with Initial Values in C++

To create a vector with specific initial values, specify the values in curly braces during vector declaration.

Syntax

The syntax to create a vector with initial values is

vector<type> vectorname{ element1, element2, .., elementN };

Examples

Integer Vector with Initial Values

In the following program, we create an integer vector with seven initial values.

main.cpp

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

int main() {
    vector<int> nums{ 1, 2, 4, 8, 16, 32, 64 };
    
    for (int n: nums) {
        cout << n << endl;
    }
}

Output

1
2
4
8
16
32
64

String Vector with Initial Values

In the following program, we create a string vector with three initial values.

main.cpp

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

int main() {
    vector<string> names{ "apple", "banana", "cherry" };
    
    for (string name: names) {
        cout << name << endl;
    }
}

Output

apple
banana
cherry

Conclusion

In this C++ Tutorial, we have learnt how to create a vector with initial values.