Without deep understanding of C++11 range based for loop, it is easy to make stupid mistakes which is hard to understand reason by reading long and complex compiler error message. Here I list what is the right and wrong format to use C++11 range based for loop.
#include <iostream>
#include <map>
#include <string>
using namespace std;
int main()
{
map<int, string> mapStudent;
mapStudent.insert(pair<int, string>(1, "student_one"));
mapStudent.insert(pair<int, string>(2, "student_two"));
mapStudent.insert(pair<int, string>(3, "student_three"));
map<int, string>::iterator iter;
// Correct iterator usage before C++11
for(iter = mapStudent.begin(); iter != mapStudent.end(); iter++)
{
cout << iter->first << " " << iter->second << endl;
}
// Wrong range based for loop usage, mix up iterator and range based for loop element
//for (iter : mapStudent) {
// cout << iter->first << " " << iter->second << endl;
//}
// Correct range based for loop usage, auto deduct element type
for (auto &elem : mapStudent) {
cout << elem.first << " " << elem.second << endl;
}
// Correct range based for loop usage, explicitly tell the compiler the element type
for (pair<int, string> elem : mapStudent) {
cout << elem.first << " " << elem.second << endl;
}
}
references:
http://www.kuqin.com/cpluspluslib/20071231/3265.html
http://en.cppreference.com/w/cpp/language/range-for
No comments:
Post a Comment