1、map的其中一個構造函數有第三個參數,可以直接定義map的key值得排序規則,
默認為std::less,即按“<”運算符進行排序
map<string, int> mapWord = { { "father", 1 },{ "mother", 4 },{ "daughter", 5 } };
等價於:
map<string, int, std::less<string>> mapWord2 = { { "father", 1 },{ "mother", 4 },{ "daughter", 5 } };
2、如果想把key值按從大到小的順序排序,改為:
map<string, int, std::greater<string>> mapWord2 ;
3、使用比較函數也可以
bool compFunc(const string& a, const string& b)
{
return a.compare(b) > 0;
}
map <string, int, decltype(compFunc)*> mapWord3; //注意*號的存在。比較操作類型必須為函數指針類型
4、使用lambda表達式
auto fc = [](const string& str1, const string& str2) {return str1.compare(str2) > 0; };
map <string, int, decltype(fc)*> mapWord4; //同樣要使用使用函數指針
5、如果key的類型是自定義的類或結構體,可以重寫“<運算符”
class A{ ... bool operator <(const A& d) { return count > d.count; } int count; } map <A, int> mapA; //關鍵字將會從大向小排列
