關於std::map的第三個參數


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;  //關鍵字將會從大向小排列

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM