map自定义排序规则

#include <iostream>
#include <map>
#include <string>
using namespace std;

struct comp
{
    bool operator()(const string &a, const string &b) const {
        if(a.length() == b.length())
            return a < b;
        if(a.length() < b.length()) {
            string tmp;
            for(int i = 0; i < b.length()-a.length(); i++)
                tmp += "0";
            return tmp+a < b;
        }
        string tmp;
        for(int i = 0; i < a.length()-b.length(); i++)
            tmp += "0";
        return a< tmp+b;        
    }   //自定义map键值的排序规则,此处是为了让string的比较得出int比较的效果  
};

int main() {
    map<string,int, comp> m_map;
    m_map.insert(pair<string,int>("100", 1));
    m_map.insert(pair<string,int>("10", 1));
    m_map.insert(pair<string,int>("1", 1));
    map<string,int>::iterator i;
    for(i = m_map.begin(); i != m_map.end(); i++)
        cout << i->first << " " << i->second << endl;  //输出顺序为1 10 100
}

猜你喜欢

转载自blog.csdn.net/chent86/article/details/78990225
今日推荐