在c++中定義了一個(gè)謂詞函數(shù):compare,用在sort函數(shù)中。但如果我將compare寫(xiě)在主函數(shù)中,在編譯階段編譯器(我用的是VS2010)會(huì)報(bào)錯(cuò),提示error C2601: “compare”: 本地函數(shù)定義是非法的。將函數(shù)定義在外部就運(yùn)行正常。想問(wèn)一下這是為什么。錯(cuò)誤程序如下:#include <iostream>#include <map>#include <string>#include <vector>#include <algorithm>using namespace std;//typedef map<string, int>::const_iterator map_it;//定義謂詞//bool compare(const map_it& lit,const map_it& rit){// return lit->second < rit->second;// }int main(){
string s;
map<string, int> counters;
typedef map<string, int>::const_iterator map_it; bool compare(const map_it& lit,const map_it& rit){ return lit->second < rit->second;
} while(cin >> s){
++counters[s];
}
//將map iterator存入vector,進(jìn)行排序
vector<map_it> itvec; for(map_it it = counters.begin(); it != counters.end(); ++it){
itvec.push_back(it);
} sort(itvec.begin(),itvec.end(),compare); for(vector<map_it>::const_iterator vit = itvec.begin(); vit != itvec.end(); ++vit)
{
cout<<(*vit)->first<<" occurs "<<(*vit)->second<<" times"<<endl;
} return 0;
}
難道謂詞函數(shù)必須在主函數(shù)外面定義嗎?還有什么函數(shù)需要定義在主函數(shù)外?
www說(shuō)
2023-04-25 19:15:08