How to iterate over changed std :: map values?

I have one std::map, and I would like to define an iterator that returns the modified values. Typically, a std::map<int,double>::iteratoriterates over std::pair<int,double>, and I would like the same behavior, just double the value being multiplied by a constant.

I tried it with boost::transform_iterator, but it does not compile:

#include <map>
#include <boost/iterator/transform_iterator.hpp>
#include <boost/functional.hpp>

typedef std::map<int,double> Map;
Map m;
m[100] = 2.24;

typedef boost::binder2nd< std::multiplies<double> > Function;
typedef boost::transform_iterator<Function, 
                                  Map::value_type*> MultiplyIter;

MultiplyIter begin = 
  boost::make_transform_iterator(m.begin(),
                                 Function(std::multiplies<double>(), 4));
// now want to similarly create an end iterator
// and then iterate over the modified map

Error:

error: conversion from 'boost
::transform_iterator<
    boost::binder2nd<multiplies<double> >, gen_map<int, double>::iterator
  , boost::use_default, boost::use_default
>' to non-scalar type 'boost::transform_iterator<
    boost::binder2nd<multiplies<double> >, pair<const int, double> *
  , boost::use_default, boost::use_default
>' requested

What is gen_mapand is it really needed?

I adapted the transform_iteratortutorial code from here to write this code ...

+3
source share
2 answers

std :: multiply, which expect double as the first argument, not std :: pair.

std:: pair ( ) , .

std:: multiply .

double times(std::pair<int,double> const& p, int i) {
  return i*p.second;
}

boost::make_transform_iterator(m.begin(),
                                 Function(times, 4));
+5
typedef boost::transform_iterator<Function, 
  Map::iterator> MultiplyIter; // value_type* only occasionally
                               // works as an iterator

gen_map - , std::map.

int*, C-.

+2

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


All Articles