how to append to a vector c++

Certainly! Here's an example of appending elements to a vector in C++:

#include <iostream>
#include <vector>

int main() {
    std::vector<int> numbers = {1, 2, 3, 4, 5};

    // Appending a single element to the vector
    numbers.push_back(6);

    // Appending multiple elements using initializer list
    numbers.insert(numbers.end(), {7, 8, 9});

    // Displaying the elements in the vector after appending
    std::cout << "Updated Vector: ";
    for (int num : numbers) {
        std::cout << num << " ";
    }
    std::cout << std::endl;

    return 0;
}

Explanation:

  1. #include <vector>: This line includes the header file necessary for using vectors in C++.

  2. std::vector<int> numbers = {1, 2, 3, 4, 5};: This creates a vector named numbers and initializes it with five integer elements.

  3. numbers.push_back(6);: This appends a single element (6 in this case) to the end of the vector using the push_back method.

  4. numbers.insert(numbers.end(), {7, 8, 9});: Here, multiple elements (7, 8, and 9) are appended to the vector using the insert method. numbers.end() signifies the position in the vector to insert the new elements, in this case, at the end of the vector.

  5. The for loop iterates through the elements in the vector numbers and prints them to the console, displaying the updated contents of the vector after appending the elements.

  6. return 0;: This line indicates the end of the main() function and signifies successful program execution.