c++ - std::set 与用户定义的类型,如何确保没有重复

标签 c++ set

所以我有一个 std::set 需要保持特定的顺序以及不允许重复用户定义的(由我)类型。现在我可以通过在我的类型中重载“<”运算符来使订单正常工作。但是,该集合没有适本地检测到重复项,老实说,我不完全确定它是如何在内部执行此操作的。我已经重载了'=='运算符,但不知何故我不确定这是该集合实际使用的内容吗?所以问题是当您添加值时,集合如何确定重复项?以下是相关代码:

用户定义类型:

//! An element used in the route calculation.
struct RouteElem {
    int shortestToHere; // Shortest distance from the start.
    int heuristic;      // The heuristic estimate to the goal.
    Coordinate position;
    bool operator<( const RouteElem& other ) const
    {
        return (heuristic+shortestToHere) < (other.heuristic+other.shortestToHere);
    }
    bool operator==( const RouteElem& other ) const
    {
        return (position.x == other.position.x && position.y == other.position.y);
    }
};

所以当它们的位置相等时,元素是等价的,如果一个元素的组合功能小于另一个元素,则它小于另一个元素。排序有效,但集合将接受相同位置的两个元素。

最佳答案

operator==未被 std::set 使用.元素 ab被认为相等当且仅当 !(a < b) && !(b < a)

关于c++ - std::set 与用户定义的类型,如何确保没有重复,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1114856/

相关文章:

sas - 在 SAS 中,位于 set 语句后面的冒号意味着什么?

c++ - 在 openacc 中为每个帮派进行递归的私有(private)数组

c++ - 错误 : expected primary-expression before ')' token

c++从控制台运行功能

flutter - Dart Set<E> 如何比较项目?

batch-file - 标签循环崩溃似乎没有原因

c++ - STL图,设置错误: memory clobbered past end of allocated block

c++ - 什么是 Trinity API

c++ - 提高生产者消费者的并发性

java - java中如何判断set是否存在?