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?
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.
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 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.
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.
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); });
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With