Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the best way to concatenate two vectors?

Tags:

c++

vector

I'm using multitreading and want to merge the results. For example:

std::vector<int> A; std::vector<int> B; std::vector<int> AB; 

I want AB to have to contents of A and the contents of B in that order. What's the most efficient way of doing something like this?

like image 979
jmasterx Avatar asked Jul 05 '10 04:07

jmasterx


People also ask

What does it mean to concatenate a vector?

Description. The Vector Concatenate and Matrix Concatenate blocks concatenate the input signals to create a nonvirtual output signal whose elements reside in contiguous locations in memory. In the Simulink® library, these blocks are different configurations of the same block.

What effect does concatenate function has on vectors?

Concatenate function: This method combines the arguments and results in a vector. All the arguments are converted to a common type that is the return value type. This function is also used to convert the array into vectors.

How do you append a vector to another vector in C++?

To insert/append a vector's elements to another vector, we use vector::insert() function. Syntax: //inserting elements from other containers vector::insert(iterator position, iterator start_position, iterator end_position);


2 Answers

AB.reserve( A.size() + B.size() ); // preallocate memory AB.insert( AB.end(), A.begin(), A.end() ); AB.insert( AB.end(), B.begin(), B.end() ); 
like image 57
Kirill V. Lyadvinsky Avatar answered Oct 21 '22 21:10

Kirill V. Lyadvinsky


This is precisely what the member function std::vector::insert is for

std::vector<int> AB = A; AB.insert(AB.end(), B.begin(), B.end()); 
like image 25
Shirik Avatar answered Oct 21 '22 20:10

Shirik