仅使用重复项创建他人的新向量

Create new vector from others, using only duplicates

本文关键字:新向量 向量 创建      更新时间:2023-10-16

假设我有一组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};

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

std::vector<int> abc = {8,2,0,8}; // possible output, order doesn't matter

我看到了许多问题,要求如何删除重复项,但我希望保留唯一

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

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

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

实时演示