C++ Vector Initialization method 01

To initialize a vector in C++, you can use the following method:

#include <vector>
using namespace std;

int main() {
    vector<int> myVector = {1, 2, 3, 4, 5};
    return 0;
}

Here is an explanation for each step:

  1. Include the vector header: The first step is to include the <vector> header file, which contains the necessary functions and definitions for using vectors in C++. This header file should be included at the beginning of your source code.
#include <vector>
  1. Declare the vector: Next, you need to declare the vector variable. In this example, we declare a vector of integers named myVector.
vector<int> myVector;
  1. Initialize the vector: To initialize the vector with specific values, you can use the initializer list syntax. In the example, we initialize myVector with the values 1, 2, 3, 4, and 5.
myVector = {1, 2, 3, 4, 5};

Alternatively, you can combine the declaration and initialization into a single step:

vector<int> myVector = {1, 2, 3, 4, 5};
  1. Access and use the vector: Once the vector is initialized, you can access and use its elements using the index operator ([]), or by using iterators. For example, to access the first element of myVector, you can use myVector[0].
int firstElement = myVector[0]; // Access the first element

That's it! You have now successfully initialized a vector in C++ using the initializer list syntax.