sortソートルール-最も完全


1.構造体外部定義ソート規則

#include 
#include 
#include 
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 
#include 
#include 
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 
#include 
#include 
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 
#include 
#include 
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;
}