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

Categories

0 votes
325 views
in Technique[技术] by (71.8m points)

dictionary - How to iterate over a C++ STL map data structure using the 'auto' keyword?

So far I have always used an iterator for traversing through all the keys in an STL map as follows:

    for (std::map<char,int>::iterator it=mymap.begin(); it!=mymap.end(); ++it){
            std::cout << it->first << "  => " << it->second << '
';
    }

Very recently though I came across some code that used a different style to iterate through the keys as shown below. Has this feature been added only recently in revised standard? It seems like a rather interesting way of getting more done with lesser code, as many other languages already provide.

    for (auto& x: mymap) {
            std::cout << x.first << " => " << x.second << '
';
    }  

Also, I am curious to know the exact implications of using the keyword "auto" here.

question from:https://stackoverflow.com/questions/14555751/how-to-iterate-over-a-c-stl-map-data-structure-using-the-auto-keyword

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

1 Answer

0 votes
by (71.8m points)

This code uses 2 new features from C++11 standard the auto keyword, for type inference, and the range based for loop.

Using just auto this can be written as (thanks Ben)

for (auto it=mymap.begin(); it!=mymap.end(); ++it)

Using just range for this can be written as

for (std::pair<const char,int>& x: mymap) {
        std::cout << x.first << " => " << x.second << '
';
}  

Both of these do the exact same task as your two versions.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

2.1m questions

2.1m answers

60 comments

57.0k users

...