一、按 key 排序
1.map顺序排序(小的在前,大的在后):
map<float,string,less<float> > m_aSort;//已float从小到大排序
2.map逆序排序(大的在前,小的在后):
map<float,string,greater<float> > m_aSortR;//已float从大到小排序
注:
用 greater_equal(less_equal) 做第三个参数来排序,map的 find 函数会失败。
如果需要存储相同key值的 键值对,可以用multimap,参见:https://www.cnblogs.com/SZxiaochun/p/10482964.html
struct SIndexData { string sCode; int iDate; int iTime; float f1; SIndexData(): iDate(0), iTime(0) { } bool operator == (const SIndexData & obj) const { return sCode == obj.sCode && iDate == obj.iDate && iTime == obj.iTime; } bool operator < (const SIndexData & obj) const { return iDate < obj.iDate ; } }; map<float, SIndexData, greater_equal<float> > m_is; SIndexData sIndexData1; sIndexData1.sCode = "000001"; sIndexData1.iDate = 20171025; sIndexData1.iTime = 94000; sIndexData1.f1 = 7.8f; m_is[sIndexData1.f1] = sIndexData1; SIndexData sIndexData2; sIndexData2.sCode = "000002"; sIndexData2.iDate = 20171025; sIndexData2.iTime = 94000; sIndexData2.f1 = 7.9f; m_is[sIndexData2.f1] = sIndexData2; SIndexData sIndexData3; sIndexData3.sCode = "000004"; sIndexData3.iDate = 20171025; sIndexData3.iTime = 94000; sIndexData3.f1 = 7.8f; //m_is[sIndexData3.f1] = sIndexData3; m_is.insert(make_pair(sIndexData3.f1, sIndexData3)); SIndexData sIndexData4 = m_is[sIndexData3.f1]; map<float, SIndexData, greater_equal<float> >::iterator iter = m_is.find(sIndexData3.f1); if (iter != m_is.end()) { cout << "find succ" << endl; } else { cout << "find error" << endl; } getchar();
原因分析参见:https://www.cnblogs.com/Harley-Quinn/p/7247978.html
二、按 value 排序
typedef pair<int, string> PAIR; bool CmpByValue(const PAIR & lhs, const PAIR & rhs) { return lhs.second < rhs.second; //按 value 从小到大排序。如果 value 不是基础类型(int、short等),而是自己定义的结构体,就在结构体中重载 < 运算符(详见:http://www.cnblogs.com/SZxiaochun/p/6377084.html 第41行)。 } map<int,string> m_two; m_two[1] = "xiaochun"; m_two.insert(make_pair(2,"chunxiao")); vector<PAIR> vPair; vPair.insert(vPair.end(), m_two.begin(), m_two.end()); sort(vPair.begin(), vPair.end(), CmpByValue);