std::map的内部排序是按照红黑树进行的,所以,查询时间复杂度为O(log2n).
参考博客:https://www.cnblogs.com/stay-alive/p/8215400.html
#include “pch.h”
#include
#include
class MyType
{
public:
MyType(int vale)
{
value = vale;
}
int GetValue()const
{
return value;
}
private:
int value;
};
class MyCompare
{
public:
bool operator()(const MyType& lhs, const MyType& rhs)const
{
return lhs.GetValue() > rhs.GetValue();
}
};
void Test()
{
std::map<MyType, std::string, MyCompare> mapValueToName;
mapValueToName[MyType(3)] = “three”;
mapValueToName[MyType(0)] = “zero”;
mapValueToName[MyType(2)] = “two”;
mapValueToName[MyType(6)] = “six”;
mapValueToName[MyType(4)] = “four”;
mapValueToName[MyType(5)] = “five”;
for (std::map<MyType, std::string, MyCompare>::iterator iter = mapValueToName.begin(); iter != mapValueToName.end(); iter++)
{
cout << "value: " << iter->first.GetValue() << " name: " << iter->second.c_str() << endl;
}
}
int main()
{
Test();
system(“pause”);
return 0;
}
结果如下图所示:
以上方式为std::map按“key”排序,接下来介绍std::map按值排序的方法!!
struct funCmpByValue {
bool operator()(const PAIR& left, const PAIR& right) {
return left.second > right.second;
}
//直接用sort对MAP排序是做不到的.可以把map装进pair里,然后将pair放入vector,自定义sort实现排序
std::vector<std::pair<std::string, double>> nameScoreArray(nameScoreMap.begin(), nameScoreMap.end());
sort(nameScoreArray.begin(), nameScoreArray.end(), funCmpByValue());
for (size_t i=0; i<nameScoreArray.size(); i++)
{
PAIR _pair = nameScoreArray[i];
std::cout << _pair.first << " : " << _pair.second << std::endl;
}