c++ - 如何合并两个不同大小的 vector 对

标签 c++ vector std-pair

我有两个 vector 想要合并为一个。两者都是嵌入式对 vector (能够在一对中保存 3 个 int 值)并且它们的大小彼此不同。

两对 vector 和合并 vector 的代码是:

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 不是“合并”两者,我想检查它是否至少将 parentVect 对添加到 mergedVect)

我的输出是:

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

vector 按对中的最后一个整数排序,所以我想要的输出是:

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

最佳答案

如果您想将两个排序序列合并为一个序列,您应该利用的算法函数是 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}

Live Example

请注意 std::sort 的用法,因为 std::merge 需要排序范围。

关于c++ - 如何合并两个不同大小的 vector 对,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52463403/

相关文章:

c++ - QAction 信号槽中的隐形 UI

c++ - 无法遍历 vector

c++ - 多线程无锁应用程序中具有多个迭代器的一个 vector

c++ - 如果 {x,y} 和 {y,x} 也被认为是相同的,那么删除 vector <pair<A,A>> 中的重复项的最简单方法是什么?

java - Swig java 进程 std::pair 与 c++ 中的类

c++ - 初始化后相同的内存地址

c++ - 从 txt 文件中读取并写入 C 中的结构

c++ - 如何调用另一个类的函数?

c++ - 如何在 C++ 中创建带有自定义比较器的 std::set?

c++ - 如何将std::pair对的迭代器传递给函数模板,并推导迭代器类型?