c++ - operator< 用于列表排序

标签 c++

我有一个简单的 Position 结构:

struct Position
{
    int x;
    int y;
};

我还有一个职位列表:

std::list<Position> positons;

我正在尝试使用 list::sort() 对列表进行排序,并且需要为 Positions 对象定义 operator<。我试着保持简单,创​​建如下内容:

bool operator<(const Position& one, const Position& two)
{
    return one.x < two.x && one.y < two.y;
}

但这行不通。我如何确定一个类/结构对象作为一个整体小于另一个?我将如何为我的 Position 结构做这件事?

编辑 当我调用 positions.sort() 时,我得到一个调试断言失败,它说: 表达式:无效运算符<

最佳答案

您当前的定义未建立 strict weak order .尝试类似的东西:

bool operator<(const Position& one, const Position& two)
{
    return std::tie(one.x, one.y) < std::tie(two.x, two.y);
}

这使用 std::tie创建两个 std::tuple<int const&, int const&>包含对 x 的引用的对象和 y one 的元素和 two , 然后使用 operator< 比较两个元组(执行 lexicographical comparison )。

std::tie需要 C++11,但使用 boost::tuple 可以获得类似的结果.

关于c++ - operator< 用于列表排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13506757/

相关文章:

c++ - 队列实现的 Malloc 指针错误

javascript - x++和++x有什么区别

c++ - 打印数组将 48 添加到预期值

c++ - ReadFile lpBuffer 参数

C++ 指向其他类函数的指针函数

c++ - MFC加载资源时如何确定默认语言ID?

android - Android JNI 代码中的 C++ 异常 - 再次

c++ - 将 2D 数组传递给 C++ 函数

包含任何类型数据的 c++ 映射,包括 vector 、映射等;没有提升

c++ - 如何使用 void 来继承变量中的信息