Hybridslinky Hybridslinky - 2 months ago 6
C++ Question

Iterating over a reference to map

I have a function returning a reference to a map, something like this:

const std::map<T1, T2>& get_some_map(void) const
{
...
}

void main(void)
{
const std::map<T1, T2>& some_map = get_some_map();
}


Now I want to iterate over this map, so I declare

std::map<T1, T2>::iterator it = some_map.begin();
const std::map<T1, T2>::iterator it_end = some_map.end();


but I get an error at the last two lines when I compile. Where am I wrong? Thank you

Answer

The type you need is const_iterator, not iterator. Even better, just use auto.