问题陈述:
我想使用自定义排序标准对结构的 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/