Lambda as OutputIterator

I come from the Java world and am not very versed in C ++, so the following question arose. I see that OutputIterator used quite widely. So far, I have seen people use insert like std::back_inserter .

Is it not possible to somehow provide a lambda that is called for each element, instead of writing the elements in the container?

Example:

Instead

 std::vector<int> my_vector; set_intersection(s1.begin(), s1.end(), s2.begin(), s2.end(), std::back_inserter(my_vector)); 

sort of

 set_intersection(s1.begin(), s1.end(), s2.begin(), s2.end(), to_iterator([](int x) { std::cout << x; })); 
+5
source share
2 answers

Boost has a function_output_iterator for this purpose:

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; })); } 

Print

 3 

It’s not too easy to write a simplified version of this (although I would prefer to use boost::iterator_facade<> for myself, so that you get stuck with a raise anyway)

+10
source

Is it not possible to somehow provide a lambda that is called for each element, instead of writing the elements in the container?

The lambda alone will not be sufficient as an argument to std::set_intersection . You will need to wrap it in a helper class (functor) that supports the requirements of OutputIterator .

The key operators supporting OutputIterator are *iter , iter++ and ++iter .

+2
source

Source: https://habr.com/ru/post/1233656/


All Articles