2016-07-03 13 views
1
/** 
* Definition for an interval. 
* struct Interval { 
*  int start; 
*  int end; 
*  Interval() : start(0), end(0) {} 
*  Interval(int s, int e) : start(s), end(e) {} 
* }; 
*/ 
class SummaryRanges { 
public: 
    SummaryRanges() { 

    } 

    void addNum(int val) { 
     auto it = st.lower_bound(Interval(val, val)); 
     int start = val, end = val; 
     if(it != st.begin() && (--it)->end+1 < val) it++; 
     while(it != st.end() && val+1 >= it->start && val-1 <= it->end) 
     { 
      start = min(start, it->start); 
      end = max(end, it->end); 
      it = st.erase(it); 
     } 
     st.insert(it,Interval(start, end)); 
    } 
private: 
    struct Cmp{ 
     bool operator()(const Interval& a, const Interval& b) { return a.start < b.start;} //works 
//  bool operator()(Interval& a, Interval& b) { return a.start < b.start;} //error 
//  bool operator()(Interval a, Interval b) { return a.start < b.start;} //works 
    }; 
    set<Interval, Cmp> st; 
}; 

私は、カスタムクラスIntervalのオブジェクトがstd::setでソートすることにしたいです。 operator()()の引数は、値またはconstのいずれかの参照になります。しかし、それは引数に非constの参照を渡すときに次のエラーを報告するでしょう。比較関数でconst参照VS非const参照対値渡し

required from ‘std::_Rb_tree<_Key, _Val, _KeyOfValue, _Compare, _Alloc>::iterator std::_Rb_tree<_Key, _Val, _KeyOfValue, _Compare, _Alloc>::lower_bound(const key_type&) [with _Key = Interval; _Val = Interval; _KeyOfValue = std::_Identity<Interval>; _Compare = SummaryRanges::Cmp; _Alloc = std::allocator<Interval>; std::_Rb_tree<_Key, _Val, _KeyOfValue, _Compare, _Alloc>::iterator = std::_Rb_tree_iterator<Interval>; std::_Rb_tree<_Key, _Val, _KeyOfValue, _Compare, _Alloc>::key_type = Interval]’ 

はなぜ失敗しstd::setに非const参照を渡すのですか?

+0

"実際には間違っているものは何かを記述しているかもしれませんが(初心者のためには幾分説明していますが)、あなたはあなたの質問の投稿に含めるべきですがエラーを報告します。 'std :: set'はコンパレータにconst参照を送ります。コンパレータが非const参照を必要とする場合は動作しません。不変参照を要求する関数に変更可能な参照を送ることができます。逆の場合はありません。 – WhozCraig

+0

エラーレポートを追加しました。ありがとうございます! – Presley

答えて

1

std::set値は不変であり、実質的にはconstです。さらに、l値参照を取るすべてのメンバ関数は、const参照をとる。 const値は非const参照にバインドできません。非const比較関数の引数に定数参照パラメータを渡すことはできません。