Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

First question: is it possible to "force" a const_iterator using auto? For example:

map<int> usa;
//...init usa
auto city_it = usa.find("New York");

I just want to query, instead of changing anything pointed by city_it, so I'd like to have city_it to be map<int>::const_iterator. But by using auto, city_it is the same to the return type of map::find(), which is map<int>::iterator. Any suggestion?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
397 views
Welcome To Ask or Share your Answers For Others

1 Answer

Sorry, but I just think the best suggestion is not using auto at all, since you want to perform a (implicitly valid) type conversion. auto is meant for deducing the exact type, which is not what you want here.

Just write it this way:

std::map<std::string, int>::const_iterator city_it = usa.find("New York");

As correctly pointed out by MooingDuck, using type aliases can improve the readability and maintainability of your code:

typedef std::map<std::string, int> my_map;
my_map::const_iterator city_it = usa.find("New York");

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...