仅使用重复项创建他人的新向量
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};
我想创建一个新的向量,以至于只有所有输入向量共有的元素输入到新向量中,如下所示:
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 << ' ';
}
实时演示
相关文章:
- 写入向量<向量<bool>>
- 如何写向量的无序向量集,即unordered_set<向量<向量<int>>集合?
- 将树节点添加到向量向量中的 n 元树遍历的平均和最坏情况时间复杂度是多少?
- C++在 2 个向量向量之间交换向量
- 使用 std::transform 将向量向量 (a) 添加到另一个向量向量 (b)
- 创建要在类中使用的向量向量,并使用 CERNROOT 绘制
- C++如何将字符数组转换为字节向量(向量<byte>)
- C++ 将地址保存为字符串的向量转换为新的向量
- 向量向量的分割错误
- 关于在向量向量上使用基于范围的 for 循环
- 为什么我不能返回向量<向量<int>>(进程返回 -1073741819 (0xC0000005))
- 有没有一种优雅的方法可以使用向量修改器并获得新的向量,而不是更改原始向量
- C++将两个不同类型的向量的属性连接到新的向量中
- 指针(指向指针)和新/malloc 向量(向量内部)c++
- 程序必须将奇数索引元素放在新的向量 C 中,将偶数索引元素放在另一个向量 T 中
- 将boost变体的向量过滤成新的向量
- 如何在每次迭代中创建新的向量
- 创建没有重复项的新排序向量
- 在不创建新子向量的情况下获取向量的范围
- 如何从另一个向量/对象集构造新的向量/指针集