Home >Backend Development >C++ >How to Concatenate Two Vectors in C Using `insert()`?
Concatenating Two Vectors
Combining two vectors is a common operation in C . Fortunately, the C Standard Library provides a straightforward way to concatenate two vectors using the insert() function.
How to Concatenate Two Vectors
To concatenate two vectors, you can use the following code:
vector1.insert(vector1.end(), vector2.begin(), vector2.end());
This code appends the elements of vector2 to the end of vector1. The insert() function takes three parameters:
By passing these parameters to the insert() function, you effectively append the elements of vector2 to the end of vector1.
Example
Consider the following example:
std::vector<int> vector1 {1, 2, 3}; std::vector<int> vector2 {4, 5, 6}; vector1.insert(vector1.end(), vector2.begin(), vector2.end()); std::cout << "Concatenated vector: "; for (int i : vector1) { std::cout << i << " "; }
Output:
Concatenated vector: 1 2 3 4 5 6
As you can see, the elements of vector2 have been successfully appended to the end of vector1.
The above is the detailed content of How to Concatenate Two Vectors in C Using `insert()`?. For more information, please follow other related articles on the PHP Chinese website!