C ++中的多键自定义排序 [英] Multi-Key Custom Sorting in C++

查看:162
本文介绍了C ++中的多键自定义排序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

问题陈述:

我想使用自定义排序标准对结构的std::vector进行排序.

I want to sort an std::vector of a structure using my custom sorting criteria.

结构为:

struct Node
{
   int x;
   int y;
   float value;
};

向量是:

std::vector<Node> vec;

我自定义的排序标准是,应首先按y然后按x对向量进行排序(就像在Microsoft Excel中一样).

My custom sorting criteria is that the vector should first be sorted by y and then by x (just like in Microsoft Excel).

输入:

x y

5 6
2 4
1 1
1 0
8 10
4 7
7 1
5 4
6 1
1 4
3 10
7 2

输出:

x y

1 0
1 1
6 1
7 1
7 2
1 4
2 4
5 4
5 6
4 7
3 10
8 10

可以通过任何C ++标准库排序功能来实现上述排序吗?如果没有,我还可以使用其他库吗?

Can the above mentioned sorting be achieved through any of the C++ Standard Library sorting functions? If not, is there any other library which I can use?

推荐答案

是的,您可以使用

Yes, you can do it using std::sort using a comparison function.

bool comparison(const Node& node1, const Node& node2)
{
    if (node1.y < node2.y) return true;
    if (node1.y == node2.y) return node1.x < node2.x;

    return false;
}

int main() {
    std::sort(vec.begin(), vec.end(), comparison);
}

这篇关于C ++中的多键自定义排序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆