Appending a vector to a vector in C++

To append a vector to another vector in C++, you can use the insert function. Here are the steps:

  1. Declare and initialize the vectors: Start by declaring and initializing the vectors that you want to append. For example, let's say we have vector vec1 and vec2 that we want to append.

  2. Determine the insertion position: Decide where you want to insert the second vector into the first vector. You can choose to insert it at the end or at any other position within the first vector.

  3. Use the insert function: To append the second vector to the first vector, use the insert function. The syntax for the function is as follows:

cpp vector1.insert(vector1.end(), vector2.begin(), vector2.end());

This line of code inserts the elements from vector2 into vector1 starting from the position specified by vector1.end() (which is the end of vector1) and ending at vector2.end() (which is the end of vector2).

  1. Verify the result: After the insertion, the first vector (vec1) will contain the elements from both vectors (vec1 and vec2).

Here is an example of appending a vector to another vector using the insert function:

#include <iostream>
#include <vector>

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

    vec1.insert(vec1.end(), vec2.begin(), vec2.end());

    for (int num : vec1) {
        std::cout << num << " ";
    }

    return 0;
}

Output:

1 2 3 4 5 6

In this example, the elements from vec2 are appended to vec1, resulting in the output [1, 2, 3, 4, 5, 6].