Lambda作为OutputIterator

Dav*_*ank 6 c++ c++11

我来自Java世界,对C++没有太多经验,所以出现了以下问题.我看到它OutputIterator被广泛使用.到目前为止我所看到的是人们使用插入器,例如std::back_inserter.

难道不可能以某种方式提供为每个元素调用的lambda而不是在容器中记录元素吗?

例:

代替

std::vector<int> my_vector;
set_intersection(s1.begin(), s1.end(), s2.begin(), s2.end(), std::back_inserter(my_vector));
Run Code Online (Sandbox Code Playgroud)

就像是

set_intersection(s1.begin(), s1.end(), s2.begin(), s2.end(), to_iterator([](int x) {
    std::cout << x;
}));
Run Code Online (Sandbox Code Playgroud)

seh*_*ehe 13

Boost就是function_output_iterator为了这个目的:

Live On Coliru

#include <boost/function_output_iterator.hpp>
#include <iostream>
#include <set>

int main() {
    std::set<int> s1{ 1, 2, 3 }, s2{ 3, 4, 5 };
    set_intersection(s1.begin(), s1.end(), s2.begin(), s2.end(),
                     boost::make_function_output_iterator([](int x) { std::cout << x; }));
}
Run Code Online (Sandbox Code Playgroud)

打印:

3
Run Code Online (Sandbox Code Playgroud)

写一个简单的版本应该不会太难(虽然我更喜欢使用boost::iterator_facade<>自己,所以你仍然会被提升所困扰)