问题陈述:
我想使用我的自定义排序标准对结构的std::vector进行排序。
结构如下:
struct Node
{
int x;
int y;
float value;
};矢量是:
std::vector<Node> vec;我的自定义排序标准是,向量应该首先按y排序,然后再按x排序(就像Microsoft中的那样)。
示例:
输入:
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++标准库排序功能来实现上述排序?如果没有,我还可以使用其他图书馆吗?
发布于 2012-11-21 15:44:41
是的,您可以使用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);
}发布于 2012-11-21 18:10:03
通常,当需要平局字典顺序时,为多个字段实现比较运算符(和函数)更清楚地表示为。
static bool compare(Node const& l, Node const& r) {
// Note the alignment so that both expressions only differ in their `l` and `r` ?
return std::tie(l.y, l.x)
< std::tie(r.y, r.x);
}然而,即使这样,也留下了一些重复和不一致的途径。以下帮助者注意到这一点:
static std::tuple<int&,int&> tuplize(Node const& n) { return std::tie(n.y, n.x); }然后可以简单地应用:
static bool compare(Node const& l, Node const& r) {
return tuplize(l) < tuplize(r);
}陶达阿姆:)
https://stackoverflow.com/questions/13496767
复制相似问题