Pregunta

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?

¿Fue útil?

Solución

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); });

Otros consejos

I agree that Dietmar Kühl's answer does exactly what was asked in the question, but I also agree with Kakadur's comment. A loop is hidden in std::transform() so the complexity is the same. Some people will judge, but if there is no direct proof of one way being better than the other, I tend to choose the most readable and least verbose version:

// create a vector of length of the smaller vector
std::vector<std::pair<int, int>> target( A.size() < B.size() ? A.size() : B.size() );

for (unsigned i = 0; i < target.size(); i++)
    target[i] = std::make_pair(A[i], B[i]);

P.S. The code above allocates just enough space for the target vector, so that the potential overhead of push_back (in case of reallocation) can be avoided.

Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top