c++ - sum elements of map by iterator -
i want sum first 4 elements of map
using iterator
in c++.
map<int, string> numbers; //making object of map numbers.insert(pair<int, string>(2,"two")); //inserting values map numbers.insert(pair<int, string>(3,"two")); //inserting values map numbers.insert(pair<int, string>(4,"two")); //inserting values map numbers.insert(pair<int, string>(7,"two")); //inserting values map numbers.insert(pair<int, string>(5,"two")); //inserting values map map<int, string>::iterator it; it=numbers.begin(); for( ;it!=numbers.begin()+4; it++){ //problem here , in body }
you can use std::accumulate
<algorithm>
header:
std::accumulate(it, std::next(it,4), 0, [](const auto& a, const auto& b){return + b.first;});
Comments
Post a Comment