Error in iterator declaration with typename map<A,B>
Jun 24, 2014 at 11:04pm UTC
I'm trying to make a silly function to show the content of maps as follows:
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
Jun 24, 2014 at 11:05pm UTC
Jun 24, 2014 at 11:10pm UTC
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.
Jun 25, 2014 at 12:34am UTC
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
Jun 25, 2014 at 12:35am UTC
Jun 25, 2014 at 4:41am UTC
or, avoid the mess with:
for ( auto it = src.begin(); ...
Or maybe go with the range-based for loop:
for ( auto& pair : src )
cout << pair.first << " ____ " << pair.second << endl ;
auto is definitely a friend to you wherever templates are involved.
Jun 25, 2014 at 7:07am UTC
Thank you everybody; it worked!
Topic archived. No new replies allowed.