C++ map常用接口

2018-08-11  本文已影响0人  林逸凡_lyf

查找key是否存在

if (enumMap.find(nFindKey) != enumMap.end()) { ... }

排序

map本身是按key排序存储的,如果想使用自定的排序规则可以传入第三参数

map<string, int, greater<string> > name_score_map; //第三个参数为比较函数,用于key的排序

如果希望使用value排序,一种办法是将map的pair存到vector中,然后使用sort函数排序

typedef pair<string, int> PAIR;
struct CmpByValue {
    bool operator()(const PAIR& lhs, const PAIR& rhs) {
        return lhs.second < rhs.second;
    }
};
int main() {
    //...
    sort(name_score_vec.begin(), name_score_vec.end(), CmpByValue());
    //...
}
上一篇 下一篇

猜你喜欢

热点阅读