C++ std :: set查找函数重载==运算符

The*_*man 8 c++ set stdset

我正在使用套装.我使用自定义结构作为键.我正在插入一个值并尝试查找插入的值.但它似乎永远找不到元素.

我已经覆盖了==运算符和<运算符.

这是结构的代码:

struct distance_t
{
 public:
int id;
double distance;

bool operator<(const distance_t& rhs) const
{
    if(distance < rhs.distance)
        return true;
    else 
        return false;
}

bool operator==( const distance_t& rhs) 
{
    if(id == rhs.id)
        return true;
    else
        return false;
}
};
Run Code Online (Sandbox Code Playgroud)

这是主要的代码

int main()
{
    set<distance_t> currentSet;

    distance_t insertDistance;
    insertDistance.id =1;
    insertDistance.distance = 0.5;

    currentSet.insert(insertDistance);

    distance_t findDistance;
    findDistance.id = 1;

    assert(currentSet.find(findDistance) != currentSet.end());
}
Run Code Online (Sandbox Code Playgroud)

它总是在assert语句中失败.我究竟做错了什么?

编辑-Ok现在我明白它根本不使用==运算符.这就是我想要的.我需要按距离排序数据结构.但我应该能够使用id删除它.有没有干净的方法或已有的数据结构来做到这一点?

jua*_*nza 8

它失败是因为您使用的distance_t::distance是比较小的比较,您没有设置findDistance:

distance_t findDistance;
findDistance.id = 1;
Run Code Online (Sandbox Code Playgroud)

std :: setoperator==用于任何东西.它只使用operator<.所以你必须改变它的逻辑才能使用distance_t::id.

如果你想在id不改变集合顺序的情况下进行搜索,你可以使用std :: find:

set<distance_t>::iterator it = std::find(currentSet.begin(), 
                                         currentSet.end(), 
                                         findDistance);
Run Code Online (Sandbox Code Playgroud)

这将使用你的operator==.请记住,这具有线性时间复杂性.