aiv*_*020 4 c++ set-intersection
给定 2 个集合(C++),有一种方便的方法可以在不进行任何分配的情况下获取交集的大小(如 std::set_intersection 所做的那样)
当然,我可以复制减去分配的实现,但我总是不愿意重新发明轮子
int count = 0;
while (first1!=last1 && first2!=last2)
{
if (*first1<*first2) ++first1;
else if (*first2<*first1) ++first2;
else {
count++; ++first1; ++first2;
}
}
Run Code Online (Sandbox Code Playgroud)
我正在考虑使用 std::set_intersection 并传递“计数”迭代器......?
在 Boost Iterator 库和 C++14 的通用 lambda 的帮助下:
#include <set>
#include <algorithm>
#include <iostream>
#include <boost/function_output_iterator.hpp>
int main()
{
std::set<int> s1 { 1,2,3,4 };
std::set<int> s2 { 3,4,5,6 };
int i = 0;
auto counter = [&i](auto){ ++i; }; // C++14
// auto counter = [&i](int ){ ++1; }; // C++11
// pre C++11, you'd need a class with overloaded operator()
std::set_intersection(
s1.begin(), s1.end(), s2.begin(), s2.end(),
boost::make_function_output_iterator(counter)
);
std::cout << i;
}
Run Code Online (Sandbox Code Playgroud)
输出是2.