• C++ STL pair


    没有找到priority_queue里存放pair不用typedef的方法...大概第一次觉得这个有用吧...

    优先队列里和sort函数对pair 的默认排序是first从小到大,second从小到大,可以自定义cmp比较函数。

    测试代码:

    #include <stdio.h>
    #include <string.h>
    #include <queue>
    #include <vector>
    #include <iostream>
    using namespace std;
    
    int main() {
        int t;
        while(cin >> t) {
            typedef pair<int, int>pa;
            priority_queue<pa, vector<pa>, greater<pa> >que;
            while(t--) {
                int a, b;
                cin >> a >> b;
                pa pairr = make_pair(a, b);
                que.push(pairr);
            }
            cout << "output-----------
    ";
            while(!que.empty()) {
                pa pairr = que.top();
                cout << pairr.first << " " << pairr.second << endl;
                que.pop();
            }
            cout << "==========
    ";
        }
        return 0;
    }
    

      

    测试代码:

    #include <stdio.h>
    #include <string.h>
    #include <queue>
    #include <vector>
    #include <algorithm>
    #include <iostream>
    using namespace std;
    
    typedef pair<int, int>pa;
    
    bool cmp(pa a, pa b) {
        if (a.second != b.second)
        return a.second > b.second;
        else return a.first > b.first;
    }
    
    int main() {
        int t;
        while(cin >> t) {
            pa pairs[10];
           for (int i=0; i<t; ++i) {
                int a, b;
                cin >> a >> b;
                pairs[i] = make_pair(a, b);
            }
    
            cout << "output-----------
    ";
            sort(pairs, pairs+t);
            for (int i=0; i<t; ++i) {
                cout << pairs[i].first << " " << pairs[i].second << endl;
            }
            cout << "==========
    ";
    
            cout << "output-----------
    ";
            sort(pairs, pairs+t, cmp);
            for (int i=0; i<t; ++i) {
                cout << pairs[i].first << " " << pairs[i].second << endl;
            }
            cout << "==========
    ";
        }
        return 0;
    }
    

      

      

  • 相关阅读:
    算法与数据结构基础
    算法与数据结构基础
    算法与数据结构基础
    分布式系统理论进阶
    分布式系统理论进阶
    分布式系统理论基础
    分布式系统理论进阶
    分布式系统理论基础
    dht 分布式hash 一致性hash区别
    排期模板
  • 原文地址:https://www.cnblogs.com/icode-girl/p/5372564.html
Copyright © 2020-2023  润新知