仅使用重复项从其他人创建新载体

Ian*_*ung 6 c++ algorithm stl

假设我有一组vector<int>

std::vector<int> a = {2,3,8,4,9,0,6,10,5,7,1};
std::vector<int> b = {6,10,8,2,4,0};
std::vector<int> c = {0,1,2,4,5,8};
Run Code Online (Sandbox Code Playgroud)

我想创建一个新向量,以使只有所有输入向量共有的元素才能输入到新向量中,如下所示:

std::vector<int> abc = {8,2,0,8}; // possible output, order doesn't matter
Run Code Online (Sandbox Code Playgroud)

我已经看到许多问题,询问如何删除重复项,但我希望保留重复项。

是否有现有的高效STL算法或结构可以为我做到这一点,还是我需要自己编写?

P.W*_*P.W 5

如前所述,您可以使用算法set_intersection 来执行此操作:但是您还必须先对vectors 进行排序

#include <iostream>
#include <vector>
#include <algorithm>
#include <iterator>
int main()
{
    std::vector<int> a = {0,1,2,3,4,5,6,7,8,9,10};
    std::vector<int> b = {0,2,4,6,8,10};
    std::vector<int> c = {0,1,2,4,5,8};

    std::vector<int> temp;
    std::vector<int> abc;

    std::sort(a.begin(), a.end());
    std::sort(b.begin(), b.end());
    std::sort(c.begin(), c.end());

    std::set_intersection(a.begin(), a.end(),
                          b.begin(), b.end(),
                          std::back_inserter(temp));

    std::set_intersection(temp.begin(), temp.end(),
                          c.begin(), c.end(),
                          std::back_inserter(abc));

    for(int n : abc)
        std::cout << n << ' ';
}
Run Code Online (Sandbox Code Playgroud)

现场演示

  • @IanYoung 1.张贴答案后,实质上不能更改问题。2.答案仍然适用于“ std :: pair”和“ int”。这个答案中没有什么是针对`int`的。 (5认同)
  • @goodvibration,您只需要足够勇敢才能经受住第一波浪潮。我的意思是,谁在乎答案在实际上是有帮助的情况下第一次投票是否被“否决”,并且从长远来看会相应地获得投票 (2认同)