rplantiko rplantiko - 1 year ago 94
C++ Question

Continue looping after a given iterator position in an std::map

I want to loop over all items of a map that follow a given item.

Unfortunately, I get the error: no match for 'operator+' (operand types are 'std::_Rb_tree_iterator >' and 'int').

What am I doing wrong?

#include <iostream>
#include <map>

int main ()
std::map<char,int> m = {

// Position at 'b' (the 'given item')
auto it = m.find('b');

// Output everything after 'b':
for (auto it1=it+1; it1!=m.end(); ++it1) {
std::cout << it1->first << " => " << it1->second << '\n';

return 0;

Answer Source

The iterator for a std::map is not random-access, so it doesn't have an operator+(). You need to use std::next() instead:

 for (auto it1=std::next(it); it1!=m.end(); ++it1) {
    std::cout << it1->first << " => " << it1->second << '\n';
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download