sort排序規則 - 最全

1. 結構體外部定義排序規則

#include <iostream>
#include <algorithm>
#include <queue>
using namespace std;
struct node
{
    int x;
};
bool cmp(node e1, node e2)
{
    /*
    1. 小於是小到大 升序
    2. 大於是大到小 降序
    */
    return e1.x < e2.x;
}
int main()
{
    node a[2];
    a[0].x = 1;
    a[1].x = 2;
    sort(a, a + 2, cmp);
    cout << a[0].x << endl
         << a[1].x;
         
    return 0;
}

2. 結構體內部的排序規則

#include <iostream>
#include <algorithm>
#include <queue>
using namespace std;
struct node
{
    int x;
    bool operator<(const node e) const
    {
        /*
        1. 把原始的放前面
        2. 小於是小到大 升序
        3. 大於是大到小 降序
        */
        return x < e.x;
    }
};
int main()
{
    node a[2];
    a[0].x = 1;
    a[1].x = 2;
    sort(a, a + 2, cmp);
    cout << a[0].x << endl
         << a[1].x;

    return 0;
}

3. 優先隊列的排序規則

和上面的正好相反

#include <iostream>
#include <algorithm>
#include <queue>
using namespace std;
struct node
{
    int x;
    bool operator<(const node e) const
    {
        /*
        1. 把原始的放前面
        2. 大於是小到大 升序
        3. 小於是大到小 降序
        */
        return x < e.x;
    }
};
int main()
{
    priority_queue<node> p;
    p.push({1});
    p.push({3});
    p.push({2});
    while (!p.empty())
    {
        cout << p.top().x << endl;
        p.pop();
    }
    return 0;
}

4. tie排序規則

#include <iostream>
#include <tuple>
#include <algorithm>
using namespace std;
int main()
{
	int a[5] = {1, 2, 3, 4, 5};
	auto cmp = [](int e1, int e2) {
		//遞減第二個放前面
		//遞增第一個放前面
		return tie(e2) < tie(e1);
	};
	sort(a, a + 5, cmp);
	for (auto e : a)
		cout << e << ' ';
	return 0;
}

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章