数据结构与算法

Java的使用Collections 类的sort方法,用返回正数时重新排序

   List<Pair<Integer,String>> list1 = new ArrayList<>();
        list1.add(new Pair(10, "aaa"));
        list1.add(new Pair(11, "cc"));
        list1.add(new Pair(12, "dd"));
        list1.add(new Pair(10, "aa"));
        list1.add(new Pair(10, "ab"));

        Comparator<Pair<Integer,String>> comparator1 = (a, b) -> {
            if (a.getKey() == b.getKey()) return a.getValue().compareTo(b.getValue()) ;//按照字典序小到大排序
            return  a.getKey()-b.getKey() ;
            //返回正数时重新排序,负数不操作,也即默认按小到大排序
        };
        Collections.sort(list1,comparator1);
        //输出结果:[10=aa, 10=aaa, 10=ab, 11=cc, 12=dd]
        System.out.println(list1);

c++使用sort方法,用vector封装,返回false重新排序

   vector<pair<int ,string>> v;
 v.push_back(pair<int ,string>(10,"aa"));
 v.push_back(pair<int ,string>(20,"bb"));
 v.push_back(pair<int ,string>(30,"cc"));
 v.push_back(pair<int ,string>(10,"a"));
 v.push_back(pair<int ,string>(10,"ab"));
 sort(v.begin(),v.end(),[&](pair<int ,string> &a,pair<int ,string> &b){
     if(a.first==b.first) return b.second>a.second;
     else return b.second>a.second;
 });
//结果10 :a ,10 : aa ,10 :ab ,20 : bb,30 :cc
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值