Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert two vectors of int with the same length into one vector of pairs of int in C++

In C++, if I have two vectors of int:

A = [1, 2, 3 ,4]; 
B = [1, 2, 3, 4]; 

How can I merge them into one vector of pairs:

[(1,1), (2,2), (3,3), (4, 4)]

Of course I can do that with a loop. But can we do that using suitable STL functions and iterators?

like image 525
David Ren Avatar asked Aug 28 '13 02:08

David Ren


People also ask

How do you input a vector into a pair?

The standard solution to add a new std::pair to a vector of pairs is using the std::emplace_back(T&&... args) function, which in-place construct and insert a pair at the end of a vector, using the specified arguments for its constructor. Note that this function is added in C++11.

Can you make a vector of pairs C++?

A vector of pairs is declared with the expression - vector<pair<int, string>> and it can be initialized the same way as the structure. Once we need to push additional std::pair type elements to the vector , the push_back method can be utilized.

What is vectors with pairs?

What is Vector of Pairs? A pair is a container which stores two values mapped to each other, and a vector containing multiple number of such pairs is called a vector of pairs.

Can we merge two vectors?

The concatenation of vectors can be done by using combination function c. For example, if we have three vectors x, y, z then the concatenation of these vectors can be done as c(x,y,z). Also, we can concatenate different types of vectors at the same time using the same same function.


1 Answers

You can use an algorithm for this:

std::vector<std::pair<int, int>> target;
target.reserve(A.size());
std::transform(A.begin(), A.end(), B.begin(), std::back_inserter(target),
               [](int a, int b) { return std::make_pair(a, b); });
like image 79
Dietmar Kühl Avatar answered Oct 22 '22 08:10

Dietmar Kühl