c++ – Wrap over an iterator for type conversion


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

In general, in simple terms, there is a container of type A, from iterator A you need to get iterator B, because the client accepts iterators B.

For instance:

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 magic_iterator_wrapper be?


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';

>>> Ditto on a real compiler <<<

Scroll to Top