c++ STL模板库的set和multiset自定义排序函数

c++ STL模板库的set和multiset自定义排序函数

以set具体说明

方法一(强烈推荐写法)

#include <iostream>
#include <set>

using namespace std;

struct node
{
    
    
    int x;
    int y;
    
    bool operator<(const node& a) const
    {
    
    
        if (a.x == x)
            return y < a.y;
        return x < a.x;
    }
};
//在 set 里面进行重载,和优先队列一样

void run_case()
{
    
    
    set<node> s;
    s.insert(node{
    
     1, 1 });
    s.insert(node{
    
     1, 1 });
    s.insert(node{
    
     1, 2 });
    s.insert(node{
    
     1, 3 });
    s.insert(node{
    
     2, 2 });
    s.insert(node{
    
     2, 3 });

    cout << s.begin()->x << " " << s.begin()->y << "\n"; // 输出 1,1
    
}

int main()
{
    
    
    run_case();
	return 0;
}

方法二(一般推荐)

#include <iostream>
#include <set>

using namespace std;

struct node
{
    
    
    int x;
    int y;
};

class comp
{
    
    
public:
    bool operator()(const node& a, const node& b) const
    {
    
    
        if (a.x == b.x)
            return a.y < b.y;
        return a.x < b.x;
    }
   
};

void run_case()
{
    
    
    set<node, comp> s;
    s.insert(node{
    
     1, 1 });
    s.insert(node{
    
     1, 1 });
    s.insert(node{
    
     1, 2 });
    s.insert(node{
    
     1, 3 });
    s.insert(node{
    
     2, 2 });
    s.insert(node{
    
     2, 3 });
    cout << s.begin()->x << " " << s.begin()->y << "\n";
}

int main()
{
    
    
    run_case();
	return 0;
}

方法三(了解就好)

#include <iostream>
#include <set>

using namespace std;

struct node
{
    
    
    int x;
    int y;
};


bool comp(const node& a, const node& b)
{
    
    
    if (a.x == b.x)
        return a.y < b.y;
    return a.x < b.x;
}

void run_case()
{
    
    
    set<node, decltype(comp)*> s(comp);
    s.insert(node{
    
     1, 1 });
    s.insert(node{
    
     1, 1 });
    s.insert(node{
    
     1, 2 });
    s.insert(node{
    
     1, 3 });
    s.insert(node{
    
     2, 2 });
    s.insert(node{
    
     2, 3 });

    cout << s.begin()->x << " " << s.begin()->y << "\n";
}

int main()
{
    
    
    run_case();
	return 0;
}

对于multiset也是一样的用法,可以自行尝试

参考资料点这里

猜你喜欢

转载自blog.csdn.net/qq_41841073/article/details/128123569
今日推荐