Iteror conversion drill



  • There are two types A and B, there is consistency between the objects of these types. There's a set of X type A values and a terator for this set. It is necessary to obtain a terator for Type B values with minimum laborators based on Hetero X.

    So, basically, there's a type A container, and it'sater A that needs a terator B, because the client accepts iterators B.

    For example:

    typedef std::pair<int, float> A;
    typedef float                 B;
    

    B A2B(const A & item) // соответствие между A и B
    {
    return item.second;
    }

    std::vector<A> X;
    input_iterator<B> bi = magic_iterator_wrapper(A2B, X.begin());

    What can be magic_iterator_wrapper?



  • We can use it. http://www.boost.org/doc/libs/1_59_0/libs/iterator/doc/transform_iterator.html

    #include <algorithm>
    #include <vector>
    #include <iostream>
    #include <boost/iterator/transform_iterator.hpp>
    

    using A = std::pair<int, float>;
    using B = float;

    float A2B(const A & item)
    {
    return item.second;
    }

    template<typename I, typename F>
    auto make_transform_iterator(I i, F f) {
    return boost::transform_iterator<F, I>{i, f};
    }

    int main() {
    std::vector<A> v = {{0, 1}, {0, 20}};

    auto first = make_transform_iterator(v.begin(), A2B);
    auto last = make_transform_iterator(v.end(), A2B);
    
    std::cout &lt;&lt; std::accumulate(first, last, 0) &lt;&lt; '\n';
    

    }

    http://coliru.stacked-crooked.com/a/aa972258d448b80e




Suggested Topics

  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2