Pvelez_3
Pvelez_3

Reputation: 115

How to merge two vector pairs of different sizes

I have two vectors that I want merged into one. Both are embedded pair vectors (to be able to hold 3 int values in one pair) and their sizes are different from eachother.

Code for the two pair vectors and the merged Vector is:

vector < pair<int, pair<int,int> > > parentVect;
vector < pair<int, pair<int,int> > > childVect;
vector < pair<int, pair<int,int> > > mergedVect;

where sizeOfFinalVect is equal to the size of both the parentVect + childVect.

parentVect = {( 0 3 9 ), ( 1 3 9 ), ( 2 2 15 )}
childVect = {( 0 1 9 )}

When I run:

 for(int i=0; i<mergedVect.size();i++){
    mergedVect.push_back(make_pair(parentVect[i].second.second, make_pair(parentVect[i].second.first, parentVect[i].first)));
}

(I know that forloop is not "merging" the two, I wanted to check if it was at least adding in the parentVect pairs to mergedVect)

my output is:

mergedVect = {( 0 0 0 ), ( 0 0 0 ), ( 0 0 0 )}

The vectors are sorted by the last integer in the pair so my desired output is:

mergedVect = {( 0 3 9 ), ( 1 3 9 ), ( 0 1 9 ), (2 2 15)}

Any help on this is greatly appreciated!

EDIT:

Using merge:

merge(parentVect.begin(), parentVect.end(), childVect.begin(), childVect.end(), std::back_inserter(mergedVect));

my output is mergedVect = {( 0 1 9 ), ( 0 3 9 ), ( 1 3 9 ), ( 2 2 15 )}

Upvotes: 0

Views: 1438

Answers (1)

PaulMcKenzie
PaulMcKenzie

Reputation: 35440

If you want to merge two sorted sequences into one sequence, the algorithm function you should be taking advantage of is std::merge.

Here is an example, using your data:

#include <vector>
#include <utility>
#include <iostream>
#include <algorithm>
#include <iterator>

typedef std::pair<int, int> PairInt;
typedef std::pair<int, PairInt> PairPairInt;
typedef std::vector<PairPairInt> PairVect;

// lambda that compares the pairs on the last value in the pair sequence
auto comparer = [](const PairPairInt& p1, const PairPairInt& p2) {return p1.second.second < p2.second.second; };

int main()
{
    PairVect parentVect = { { 0,{ 3, 9 } },{ 1,{ 3, 9 } },{ 2,{ 2, 15 } } };
    PairVect childVect = { { 0,{ 1, 9 } } };
    PairVect mergedVect;

    // First, sort the sequences based on the criteria that the
    // last number in the pairs is sorted in ascending order
    std::sort(parentVect.begin(), parentVect.end(), comparer);
    std::sort(childVect.begin(), childVect.end(), comparer);

    // Now merge the two sequences above, using the same sorting criteria
    std::merge(parentVect.begin(), parentVect.end(), 
               childVect.begin(), childVect.end(), 
               std::back_inserter(mergedVect), comparer);

    for (auto& p : mergedVect)
        std::cout << "{" << p.first << " " << p.second.first << " " << p.second.second << "}\n";
}

Output:

{0 3 9}
{1 3 9}
{0 1 9}
{2 2 15}

Live Example

Note the usage of std::sort, as std::merge requires sorted ranges.

Upvotes: 1

Related Questions