vector insert to end

To insert an element at the end of a vector in C++, you can use the push_back() function. Here are the steps to do so:

  1. Declare a vector variable: Start by declaring a vector variable, specifying the data type of the elements it will hold. For example, to create a vector of integers, you would write:
vector<int> myVector;
  1. Initialize the vector: You can initialize the vector with elements if needed. For example, to initialize a vector with three integers, you would write:
vector<int> myVector = {1, 2, 3};
  1. Insert the element at the end: To insert an element at the end of the vector, you can use the push_back() function. This function takes the value of the element you want to insert as its argument. For example, to insert the value 4 at the end of the vector, you would write:
myVector.push_back(4);
  1. Access the elements: You can access the elements of the vector using the indexing operator [] or the at() function. For example, to access the first element of the vector, you would write:
int firstElement = myVector[0];

or

int firstElement = myVector.at(0);
  1. Print the vector: Finally, you can print the vector to verify that the element has been inserted at the end. You can use a loop to iterate over the elements of the vector and print them one by one. For example:
for (int i = 0; i < myVector.size(); i++) {
    cout << myVector[i] << " ";
}

This will output:

1 2 3 4

That's it! You have successfully inserted an element at the end of a vector in C++.