今天使用std::for_each分别对Qt的QMap和C++标准库的map进行遍历,结果出乎意料。下面直接看代码。
#include <QtCore/QCoreApplication>
#include <QMap>
#include <map>
#include <iostream>
#include <algorithm>
using namespace std;
int main(int argc, char *argv[])
{
QCoreApplication a(argc, argv);
QMap<char*, int> qtMap;
qtMap["1"] = 1;
qtMap["2"] = 2;
qtMap["3"] = 3;
qtMap["4"] = 4;
qtMap["5"] = 5;
cout<<"QMap for_each:"<<endl;
for_each(qtMap.begin(), qtMap.end(), [](int num){
cout<<num<<endl;
});
map<char*, int> stdMap;
stdMap["1"] = 1;
stdMap["2"] = 2;
stdMap["3"] = 3;
stdMap["4"] = 4;
stdMap["5"] = 5;
cout<<"std::map for_each:"<<endl;
for_each(stdMap.begin(), stdMap.end(), [](const pair<char*,int> &pair){
cout<<pair.first<<":"<<pair.second<<endl;
});
return a.exec();
}
看出来了吧。QMap的for_each谓词参数是其value,而std::map的谓词参数则是pair<char*,int>。好吧。这些异同着实让我有点措手不及。不过还好发现的早。不知道为啥会这样。按理说应该是std::map的pair做为谓词参数。先这样吧,记着以后注意。