C++ Vector Initialization method 03
To initialize a C++ vector, you can use the following method:
#include <iostream>
#include <vector>
int main() {
std::vector<int> myVector = {1, 2, 3, 4, 5};
return 0;
}
Let's break down this code and explain each step:
Include the necessary headers: The code begins by including the necessary headers,
<iostream>
and<vector>
, which provide the functionality for input/output and vectors, respectively.Declare the main function: The
main
function is the entry point of the program. It is where the execution begins.Declare a vector: The line
std::vector<int> myVector
declares a vector namedmyVector
that stores integers. Thestd::vector
is a container class from the Standard Template Library (STL) that provides dynamic array-like functionality.Initialize the vector: The line
myVector = {1, 2, 3, 4, 5}
initializes the vector with the values{1, 2, 3, 4, 5}
. This is done using the initializer list syntax, where the values are enclosed in curly braces{}
.Return 0: The
return 0
statement indicates that the program executed successfully.
By following these steps, you can initialize a C++ vector with a set of values using the initializer list syntax.