仅使用重复项从其他人创建新载体 [英] Create new vector from others, using only duplicates
本文介绍了仅使用重复项从其他人创建新载体的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
比方说我有一组 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};
我想创建一个新向量,使所有输入都只有相同的元素向量被输入到新向量中,如下所示:
I want to create a new vector, in such a way that only elements which are common to all input vectors are input into the new vector as follows:
std::vector<int> abc = {8,2,0,8}; // possible output, order doesn't matter
我看到很多问题询问如何删除重复项,但我希望仅保留 重复项。
I have seen many questions asking for how to remove duplicates, but I wish to retain only duplicates.
是否存在现有的有效STL算法或结构可以
Is there an existing efficient STL algorithm or construct that will do this for me, or do I need to write my own?
推荐答案
如上所述,您可以使用算法 set_intersection 即可:
但是您还必须对<$ c $进行排序c> vector 第一个
As mentioned, you can use an algorithm set_intersection to do this:
But you will also have to sort the vector
s first
#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 << ' ';
}
这篇关于仅使用重复项从其他人创建新载体的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文