Home >Backend Development >C++ >How Can I Efficiently Concatenate Multiple std::vectors in C ?

How Can I Efficiently Concatenate Multiple std::vectors in C ?

Mary-Kate Olsen
Mary-Kate OlsenOriginal
2024-12-18 01:29:10483browse

How Can I Efficiently Concatenate Multiple std::vectors in C  ?

Concatenating Multiple std::Vectors

Concatenating two or more std::vectors is a common task in C programming. Here's how you can do it:

Using the insert() Method

The insert() method allows you to insert elements at a specific position in a vector. To concatenate two vectors, insert the second vector at the end of the first vector as follows:

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

This will append the elements of vector2 to the end of vector1, effectively concatenating the two vectors.

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 num : vector1) {
  std::cout << num << " ";
}

Output:

Concatenated Vector: 1 2 3 4 5 6

The above is the detailed content of How Can I Efficiently Concatenate Multiple std::vectors in C ?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
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