【问题标题】:C++ - Sorting first and second of a vector of pair at the same timeC ++ - 同时对一对向量的第一个和第二个进行排序
【发布时间】:2020-05-19 00:51:50
【问题描述】:
vector<pair<int, char>> pair_vec;

我有这样一个包含对的向量。我想按降序对第二对进行排序,如果有两对具有相同的char 值,那么这两个应该按第一对升序排序。

sort(pair_vec.begin(), pair_vec.end(), sortbysecdesc);

这是我用来对向量进行排序的代码。但它只能根据对中的第二个进行排序。

bool sortbysecdesc(const pair<int,char> &a, const pair<int,char> &b) {
       return a.second > b.second;
}

这是我使用的驱动函数。如果几秒钟相同,我如何编码以升序对向量进行排序

【问题讨论】:

    标签: c++ sorting


    【解决方案1】:

    使用这个-

    bool sortbysecdesc(const pair<int,char> &a, const pair<int,char> &b) {
           if(a.second==b.second)
                return a.first<b.first;
           return a.second > b.second;
    }
    

    【讨论】:

      【解决方案2】:

      将二进制函数更改为

      bool sortbysecdesc(const pair<int,char> &a, const pair<int,char> &b) {
          return (a.second == b.second) ? a.first < b.first : a.second > b.second;
      }
      

      【讨论】:

        【解决方案3】:

        您需要检查second值是否相等,如果相等则返回比较first值的结果,否则返回比较second值的结果:

        bool sortbysecdesc(const pair<int,char> &a, const pair<int,char> &b) {
            return (a.second == b.second) ? (a.first < b.first) : (a.second > b.second);
        }
        

        例如:

        vector<pair<int, char>> pair_vec{ {1,'a'}, {2,'b'}, {3,'b'}, {4,'b'}, {5,'f'}, };
        sort(pair_vec.begin(), pair_vec.end(), sortbysecdesc);
        for (auto &p : pair_vec)
            cout << p.first << ' ' << p.second << endl;
        

        输出:

        5楼 2 乙 3 乙 4 乙 1个

        Live Demo

        【讨论】:

          猜你喜欢
          • 2021-09-25
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2020-12-04
          • 2020-08-01
          • 1970-01-01
          相关资源
          最近更新 更多