c++ - 减去包含重复元素的 vector

标签 c++ vector duplicates set-intersection

是否有任何优雅的方法来减去包含重复元素的 std::vector


例子:

v1 = { 3, 1, 2, 1, 2, 2 }
v2 = { 2, 4, 3, 3, 3 }
result1 = ??( v1, v2 )
result2 = ??( v2, v1 )

我希望结果是:

result1 = { 1, 1 }
result2 = { 4 }

我目前(而且非常慢)的解决方案:

1) sort v1 and v2
2) use std::unique_copy to v1_uniq, v2_uniq
3) intersect the new vectors with std::set_intersection
4) iterate over v1 and v2 and remove all elements, that are in the intersection 3)

我的另一个想法是:

1) sort v1 and v2
2) iterate over v1 and v2 and remove duplicates in parallel 

但这有点容易出错,在我看来并不优雅。

还有其他想法吗?

最佳答案

你可以使用 std::copy_if使用一元谓词检查元素是否在第二个 vector 中。或者,如果您不支持 C++11,请使用 std::remove_copy_if适当更改谓词的逻辑。

对于一元谓词:

struct Foo {

  Foo(const std::vector& v) : v_(v) {}
  bool operator() (int i) const {
    // return true if i is in v_
  }
  const std::vector<int>& v_;

};

可以像这样实例化:

Foo f(v2);

您可以修改仿函数以保留引用 vector 的排序版本,并使用唯一条目以允许进行二分搜索,但总体思路是相同的。

关于c++ - 减去包含重复元素的 vector ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10968319/

相关文章:

c++ - 使用位域的结构大小不正确

c++ - 在 Xwindow 中访问其他窗口的标题

c++ - 两个 time_point 实例之间的差异不是持续时间吗?

r - 具有原始向量的所有不同值的最小子向量

对象和指针的 C++ vector

python - Python 中的重复数据删除

MYSQL 使用 SELECT DISTINCT 重复记录

c++ - 用gdb调试的时候,汇编代码前面的调试信息是什么意思?

php - 删除重复的 MySQL 查询结果?

c++ - 数组中的 SIGABRT C++ 如何转向 <vector>