对Map按value进行排序

原创
2017/08/04 23:57
阅读数 368
 

Map内部是按key进行排序的,而不是value

如果希望根据valueMap里面的元素对排序,可以通过把Map里面的元素拷贝到一个list中,然后定义自己的比较函数,并对该list进行排序。

1)首先,需要定义一个结构体,以用于封装Map中的元素对(key, value)

struct strTest

{

    char key[32]; //key示例

    unsigned int value; //value示例

};

typedef std::list<stFunc> tpTestList;

tpTestList testList;

typedef std::map<char*, unsigned int> tpTestMap;

tpTestMap testMap;

(2)定义一个对结构体进行比较的函数

static bool xx_greater(strTest f1, strTest f2)

{

    return f1.value<f2.value;

}

(3)遍历map,将其元素拷贝到list中;使用上面定义的比较函数,直接调用list的sort方法,即可实现排序

/* copy map to a list, to enable sort by value

Example:

{{"key1",10},{"key2",2},{"key3",5}}

=>{{"key2",2},{" key3",5},{"key1",10}}

*/

static void xx_sort()

{

    testList.clear();

    tpTestMap::iterator pos;

    for (pos=testMap.begin(); pos!=testMap.end(); ++pos)

    {

       strTest test;

       strcpy(test.key, pos->first);

       test.value = pos->second;

       testList.push_back(test);

    }

    testList.sort(xx_greater);

}


展开阅读全文
加载中
点击引领话题📣 发布并加入讨论🔥
打赏
0 评论
0 收藏
0
分享
返回顶部
顶部