我给出了两组(从std :: <set>
设置std ::),我想知道大小的交集。我可以使用<algorithm>
中的std :: set_intersection,但我必须为它提供一个输出迭代器以将交集复制到其他容器中。如何计算C++中两个STL集的交集的大小
一个直接的方法将是
set<int> s1{1,2,3,4,5};
set<int> s2{4,5,6,7,8,9,0,1};
vector<int> v;
set_intersection(
s1.begin(), s1.end(), s2.begin(), s2.end(),
inserter(v, v.begin()));
之后v.size()给出了交集的大小。但是,交叉点也必须存储,即使我们对此不做任何处理。
为了避免这种情况,我想实现一个虚拟输出迭代器类,仅计算,但它不会给:
template<typename T>
class CountingOutputIterator {
private:
int* counter_;
T dummy_;
public:
explicit CountingOutputIterator(int* counter) :counter_(counter) {}
T& operator*() {return dummy_;}
CountingOutputIterator& operator++() { // ++t
(*counter_)++;
return *this;
}
CountingOutputIterator operator++(int) { // t++
CountingOutputIterator ret(*this);
(*counter_)++;
return ret;
}
bool operator==(const CountingOutputIterator& c) {
return counter_ == c.counter_; // same pointer
}
bool operator!=(const CountingOutputIterator& c) {
return !operator==(c);
}
};
使用,我们可以做
set<int> s1{1,2,3,4,5};
set<int> s2{4,5,6,7,8,9,0,1};
int counter = 0;
CountingOutputIterator<int> counter_it(&counter);
set_intersection(
s1.begin(), s1.end(), s2.begin(), s2.end(), counter_it);
之后计数器保存交集的大小。
然而,这是更多的代码。我的问题是:
1)是否有标准(库)方式或标准技巧来获取交叉点的大小而不存储整个交集? 2)独立于是否存在,是否使用自定义虚拟迭代器是一种好方法?
似乎过于复杂,只是确定共同元素的数量。为什么不使用循环? – Aldehir
很奇怪,当你从未真正使用十字路口时,知道大小的意义何在?你在想这个吗? [阅读此](http://meta.stackexchange.com/questions/66377/what-is-the-xy-problem)。 –
而不是一个自定义的迭代器,创建一个自定义的“容器”,该容器具有一个“insert()”成员,可以计算和使用insert_iterator。 –