I wondered,
for(std::map<int, double, std::greater<int> >::iterator it = mymap.begin(); it != mymap.end(); ++it)
{
//do stuff
}
Why am I not able to write this as:
for(mymap::iterator it = mymap.begin(); it != mymap.end(); ++it)
{
//do stuff
}
Of course, typedeffing the map would make the first code less verbose - but that is not my point. The compiler knows the type of mymap
, so why not let it resolve mymap::iterator
? Is there a reason why iterator
is not accessible via the instance?
::
is a scope resolution operator that expects type name or namespace name on the left-hand side. It doesn't accept object names on the left-hand side. Allowing this would probably overcomplicate a lot of things in the language.
In fact, if one would to allow something like this, one'd probably attach this functionality to .
operator, since .
operator is the one used with objects on the LHS
for (mymap.iterator it = mymap.begin(); it != mymap.end(); ++it)
But this still would unnecessarily overcomplicate things anyway.
In the future C++ standard something like that will become possible through decltype
keyword
for (decltype(mymap)::iterator it = mymap.begin(); it != mymap.end(); ++it)
P.S. According to Wikipedia article on decltype
, its availability in qualified-ids was a matter of debate. If I understood it correctly, this usage was eventually voted in.
P.P.S. Also, as @Asha noted in comments, in the future C++ you'll be able to avoid naming the type at all
for (auto it = mymap.begin(); it != mymap.end(); ++it)
That iterator is a type which is defined in the scope of map and not part of objects created from map.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With