rplantiko rplantiko - 18 days ago 5
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 = {
{'a',1},{'b',2},{'c',3},{'d',4},
};

// 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

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';
 }