c++ - Adding all values of map using std::accumulate -


i trying add values of map defined in program below:

std::map<int, int> floor_plan;  const size_t distance = std::accumulate(std::begin(floor_plan), std::end(floor_plan), 0);  std::cout << "total: " << distance; 

i following error:

error c2893: failed specialize function template 'unknown-type std::plus::operator ()(_ty1 &&,_ty2 &&) const'

std::begin(floor_plan) gives iterator pointing @ std::map<int, int>::value_type std::pair<const int, int>. since there no operator+ defined pair type , integer, code fails compile.

option #1

if want sum mapped values floor_plan, you'd need provide own binary operator able extract second element of dereferenced iterator passed in:

std::accumulate(std::begin(floor_plan)               , std::end(floor_plan)               , 0               , [] (int value, const std::map<int, int>::value_type& p)                    { return value + p.second; }                ); 

demo 1

option #2

alternatively, exploit boost.iterator library extract second element of pair on fly boost::make_transform_iterator:

#include <boost/iterator/transform_iterator.hpp> #include <functional>  auto second = std::mem_fn(&std::map<int, int>::value_type::second); std::accumulate(boost::make_transform_iterator(std::begin(floor_plan), second)               , boost::make_transform_iterator(std::end(floor_plan), second)               , 0); 

demo 2

option #3

another approach use boost.range library along own implementation of accumulate algorithm:

#include <boost/range/numeric.hpp> #include <boost/range/adaptor/map.hpp>  boost::accumulate(floor_plan | boost::adaptors::map_values, 0); 

demo 3


Comments

Popular posts from this blog

java - Andrioid studio start fail: Fatal error initializing 'null' -

android - Gradle sync Error:Configuration with name 'default' not found -

StringGrid issue in Delphi XE8 firemonkey mobile app -