Iterating over objects that are at the intersection of two ranges

Is there something in the standard library that allows me to iterate over objects that are contained in the intersection of two ranges?

Specifically given the function object action

, I want to get a program that is equivalent to

/* some container supporting a push_back operation */ intersection;
std::set_intersection(first1, last1, first2, last2,
    std::back_inserter(intersection));
for (auto const& element : intersection)
    action(element);

      

without having to insert into intersection

. Of course, it's easy to write code like this, like

template<class InputIt1, class InputIt2, class UnaryFunction>
void for_each_in_intersection(InputIt1 first1, InputIt1 last1,
    InputIt2 first2, InputIt2 last2, UnaryFunction f)
{
    while (first1 != last1 && first2 != last2)
    {
        if (*first1 < *first2)
            ++first1;
        else
        {
            if (!(*first2 < *first1))
                f(*first1++);
            ++first2;
        }
    }
}

      

but I hope the standard library already has something.

+3


source to share


2 answers


You can use Function Iterator from boost:



#include <boost/function_output_iterator.hpp>
#include <vector>
#include <iostream>
#include <algorithm>

int main() {
    std::vector<int> v1 = {1, 2, 3, 4, 5};
    std::vector<int> v2 = {2, 4};
    std::set_intersection(v1.begin(), v1.end(), v2.begin(), v2.end(),
            boost::make_function_output_iterator([](int i) {
                std::cout << i * i << '\n';
            }));
}

      

+6


source


I don't know of anything in STL that can do what you want better than codes.

Easier, I think, includes std::for_each()

, std::find()

std::binary_search()

(thanks Rakete1111) and the lambda function. But I don't think it's a good idea because it doesn't use the factthat the containers are ordered. ordered values ​​are ordered.



Below is a complete working example

#include <vector>
#include <iostream>
#include <algorithm>

template <typename T>
void action (T const & val)
 { std::cout << "- action over " << val << std::endl; }

int main()
 {
   std::vector<int> v1 { 11, 12, 13, 14, 15, 16, 17, 18, 19, 20 };
   std::vector<int> v2 { 2, 3, 5, 7, 11, 13, 17, 19, 23, 29 };

   std::for_each(v1.cbegin(), v1.cend(),
                 [&](int val) {
      if ( std::binary_search(v2.cbegin(), v2.cend(), val) )
         action(val);
    });
 }

      

+1


source







All Articles