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; } );
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);
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);
Comments
Post a Comment