Home > Backend Development > C++ > How to Concatenate Two Vectors in C Using `insert()`?

How to Concatenate Two Vectors in C Using `insert()`?

Patricia Arquette
Release: 2024-12-22 17:17:15
Original
262 people have browsed it

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());
Copy after login

This code appends the elements of vector2 to the end of vector1. The insert() function takes three parameters:

  • The iterator pointing to the insertion point (in this case, vector1.end(), which points to the end of vector1)
  • The iterator pointing to the beginning of the elements to insert (in this case, vector2.begin())
  • The iterator pointing to the end of the elements to insert (in this case, vector2.end())

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 << " ";
}
Copy after login

Output:

Concatenated vector: 1 2 3 4 5 6
Copy after login

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!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template