Error in iterator declaration with typename map<A,B>

I'm trying to make a silly function to show the content of maps as follows:

1
2
3
4
5
6
7
8
9
10
template<typename A, typename B>
void show_map(const std::map<A,B> &src)
{
    for( std::map<A,B>::iterator it=src.begin(); it!=src.end(); ++it )
    {
	  
    cout << it->first << " ____ " << it->second << endl;
    
    }	
};


However, I got this error in the 'for' line: "error: expected ‘;’ before ‘it’" (and then errors that it is not declared, etc). I'm sure that there is no missing ; in other functions. If you try to write a random line before that you get no error there for example, always in the for.

It is there something that you need to do with iterators when you declare generic datatypes?
Last edited on
Well, I just tried it and I only had one error: You need to use const_iterator instead of iterator because src is const. Other than that it compiled fine for me.
Apart from that
gcc wrote:
In function ‘void show_map(const std::map<A, B>&)’:
error: need ‘typename’ before ‘std::map<A, B>::iterator’ because ‘std::map<A, B>’ is a dependent scope
clang wrote:
error: missing 'typename' prior to dependent type name 'std::map<A, B>::iterator'


So it should be for( typename std::map<A,B>::const_iterator it = src.begin();
Last edited on
or, avoid the mess with:

for ( auto it = src.begin(); ...

Or maybe go with the range-based for loop:

1
2
    for ( auto& pair : src )
        cout << pair.first << " ____ " << pair.second << endl ;


auto is definitely a friend to you wherever templates are involved.
Thank you everybody; it worked!
Topic archived. No new replies allowed.