stl map容器按值排序

来源:互联网 发布:c 低级编程 编辑:程序博客网 时间:2024/06/05 00:09

stl中的map 没有其他容器的sort函数,当需要按值排序时,可以按着如下方式进行排序。

#include <iostream>#include <map>#include <vector>#include <algorithm>#include <string>bool cmp_by_value(const std::pair<int , double> &lhs , const std::pair<int , double> &rhs){    return lhs.second < rhs.second ;}struct CmpByValue{    bool operator()(const std::pair<int , double> &lhs , const std::pair<int , double> &rhs)    {        return lhs.second < rhs.second ;    }};int main(){    std::map<int , double> mp ;    mp.insert(std::pair<int , double>(1 , 0.2)) ;    mp.insert(std::pair<int , double>(2 , 0.1)) ;    mp.insert(std::pair<int , double>(3 , 0.1)) ;    std::vector<std::pair<int , double> > vec(mp.begin() , mp.end()) ;    std::sort(vec.begin() , vec.end() , CmpByValue()) ;    for (int i = 0 ; i < vec.size() ; ++i)    {        std::cout<<vec[i].first<<","<<vec[i].second<<std::endl ;    }    std::system("pause") ;    return 1 ;}

这里写图片描述

0 0
原创粉丝点击