C++结构集无法按元素查找/擦除

C++ set of struct fails to find/erase by element

本文关键字:元素 查找 擦除 结构 C++      更新时间:2023-10-16

如下所示,y 轴间隔集(即垂直(需要满足两个要求:

1(它从下到上对所有间隔进行排序;

2( 如果新间隔与设置中的任何间隔重叠,则返回插入失败。这类似于 STL set<int>在插入重复的 int 时返回pair.second == false

我的猜测是自定义比较功能cmp_set导致了查找/擦除失败的错误,间隔的顺序也是降序的(应该是升序?由于 STL 集依赖于查找区间的二叉搜索,因此它失败了。

如何解决这个问题?问题是比较函数cmp_set应该处理上述两个要求 1( 和 2(,但返回 int 值为 -1/1/0 似乎不起作用。将其更改为布尔比较函数仅返回 true/false,无法检测重叠间隔。

#include <iostream>
#include <string>
#include <set>
using namespace std;
struct Interval {
    int down;
    int up; 
    Interval(int d, int u) {
        down = d;                        
        up = u;
    }   
    bool operator==(const Interval& other) {
        return down == other.down && up == other.up;
    }   
};
auto cmp_set = [](const Interval& a, const Interval& b) {
    // if (a.up <= b.down) {//a's up is below b's down
    //     return -1;  //sort a before b, like a < b 
    // } else if (a.down >= b.up) {//a's down is above b's up
    //     return 1; //sort a after b, like a > b 
    // } else {
    //     return 0; //overlap. Very similar to the Interval Overlap
    // }
    if (max(a.down, b.down) < min(a.up, b.up)) return 0; //overlap of intervals
    else { //sort the two intervals 
        if(a.up <= b.down) return -1; 
        else return 1;
    }   
};        
void print(set<Interval, decltype(cmp_set)>& s) {
    for (auto it = s.begin(); it != s.end(); it++) {
        cout << it->down << "->" << it->up << ", ";
    }                                
    cout << endl;
}

int main()
{
    set<Interval, decltype(cmp_set)> s(cmp_set);

    s.insert(Interval{1, 3});
    s.insert(Interval{3, 4});
    print(s); //3->4, 1->3, 
    auto iter = s.find(Interval{3, 4});
    if (iter == s.end()) cout << "not find" << endl; //not find
    s.erase(Interval{3, 4});  //fail to remove the Interval
    print(s); //still contains 3->4, 1->3, 
    return 0;
}