c++ - C++ 中的多键自定义排序

标签 c++ sorting vector struct

问题陈述:

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

结构是:

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

vector 是:

std::vector<Node> vec;

我的自定义排序标准是 vector 应首先按 y 排序,然后按 x 排序(就像在 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++标准库的排序函数实现上述排序?如果没有,是否还有其他我可以使用的库?

最佳答案

是的,您可以使用 std::sort 来完成使用比较函数。

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++ - C++ 中的多键自定义排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13496767/

相关文章:

c++ - 计算一个巨大的c++程序的运行时间

c++ - 将单个数组复制到多维数组

sql - sql中基于频率的排序

R 根据自己的意愿对向量进行排序

c++ - 包含原子的类的 std::vector

C++ 在编译时将图像像素嵌入 vector 内?

c++ - 将 wxString 转换为 time_t

c++ - 使用枚举处理错误

c++ - 无法在 QStyledItemDelegate 中绘制复选框

algorithm - 归并排序算法困境