Как объединить две пары векторов разных размеров - PullRequest
0 голосов
/ 23 сентября 2018

У меня есть два вектора, которые я хочу объединить в один.Оба являются встроенными парными векторами (чтобы иметь возможность хранить 3 значения int в одной паре), и их размеры отличаются друг от друга.

Код для двух парных векторов и объединенного вектора:

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

, где sizeOfFinalVect равен размеру обоих parentVect + childVect.

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

Когда я запускаю:

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

(я знаю, что forloop не «объединяет» два, я хотел проверить, добавлял ли он по крайней мере добавление в родительские пары в mergedVect)

мой вывод:

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

Векторы отсортированы по последнему целому числу в паре, поэтому мой желаемый результат:

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

Любая помощь по этому вопросу очень ценится!

РЕДАКТИРОВАТЬ:

Использование слияния:

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

мой вывод mergedVect = {(0 1 9), (0 3 9), (1 3 9),(2 2 15)}

1 Ответ

0 голосов
/ 23 сентября 2018

Если вы хотите объединить две отсортированные последовательности в одну последовательность, функция алгоритма, которой вы должны воспользоваться: std :: merge .

Вот пример использования ваших данных:

#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";
}

Вывод:

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

Живой пример

Обратите внимание на использование std::sort, так как std::merge требует отсортированных диапазонов.

...