To initialize a vector in C++, you can use the std::vector
class from the Standard Template Library (STL), which allows you to create dynamic arrays.
In this example,
header to use the std::vector
class.std::vector
and provide a list of initial values enclosed in curly braces.int_vector
.#include <iostream>
#include <vector>
int main() {
std::vector<int> int_vector = {1, 2, 3, 4, 5};
for (int num : int_vector) {
std::cout << num << " ";
}
return 0;
}
1 2 3 4 5
In this example,
and
headers to use the std::vector
and std::string
classes.std::vector
and provide a list of initial values enclosed in curly braces.str_vector
.#include <iostream>
#include <vector>
#include <string>
int main() {
std::vector<std::string> str_vector = {"apple", "banana", "cherry"};
for (const std::string& str : str_vector) {
std::cout << str << " ";
}
return 0;
}
apple banana cherry
In this example,
header to use the std::vector
class.std::vector
and provide a list of initial values enclosed in curly braces.bool_vector
.#include <iostream>
#include <vector>
int main() {
std::vector<bool> bool_vector = {true, false, true};
for (bool val : bool_vector) {
std::cout << std::boolalpha << val << " ";
}
return 0;
}
true false true
In this tutorial, we learned How to Initialize a Vector in C++ language with well detailed examples.