In this C++ tutorial, you will learn how to create a vector with initial values using curly braces in the vector declaration, with example programs.
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
</>
Copy
vector<type> vectorname{ element1, element2, .., elementN };
Examples
1. Create integer vector with initial values
In the following program, we create an integer vector with seven initial values.
main.cpp
</>
Copy
#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
2. Create string vector with initial values
In the following program, we create a string vector with three initial values.
main.cpp
</>
Copy
#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.