There are two types A and B, a correspondence is established between the objects of these types. There is a set of X values ​​of type A and an iterator on this set. It is necessary with minimal effort based on the X iterator to get an iterator on the values ​​of type B.

In general, simply speaking, there is a container of type A, from iterator A you need to get iterator 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 could be magic_iterator_wrapper ?

  • If I understand your question correctly, every object of type A knows about an object of type I. But it is not entirely clear how a set of objects of type A will know about a set of objects of type B. For example, if the first object from set A corresponds to the last object from set B. Or do you need an iterator on the virtual, non-existent in reality set B? - VladD pm
  • @VladD Yes, you understood correctly. In a simple way, there is a container of type A, from iterator A you need to iterate B because the client accepts iterators B. I’ve misplaced the question too elaborately. - Cerbo

1 answer 1

You can use boost::transform_iterator

 #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 << std::accumulate(first, last, 0) << '\n'; } 

>>> The same on a real compiler <<<

  • I tried to apply it first, but it does not allow the resulting type to be different from the original one. Asertami swears. Here's boost.org/doc/libs/1_59_0/libs/iterator/doc/… - Cerbo
  • My assertions do not work. - Abyx
  • If so, maybe it makes sense to try on versions of boost? - VladD 2:21 pm
  • Or compiler. Or the real code on which the error is reproduced. - Abyx
  • They do not need to measure, I just did not know how to cook it. Everything is working. - Cerbo