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

时间:2019-04-02 06:17:52

标签: c++ set

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

1)它将所有间隔从下到上排序;

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

我的猜测是定制的比较功能cmp_set导致查找/擦除失败的错误,间隔的顺序也降序(应升序)。由于STL集依赖于二进制搜索来查找间隔,因此失败。

应如何解决?问题在于比较函数cmp_set将满足上述两个要求1)和2),但是返回int值,因为-1/1/0似乎不起作用。将其更改为bool比较功能只会返回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;
}

1 个答案:

答案 0 :(得分:0)

如果我正确理解您的比较,则需要以下设置:

auto cmp_set = [](const Interval& a, const Interval& b) { 
    return a.down >= b.up; 
}

意思是,如果a在集合中位于b之前,则a将在b结束之后开始。

当!(a