c++ - 比较函数中按值传递、非常量引用与常量引用

标签 c++ arguments comparator

/**
 * 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 引用时,它会报告以下错误。

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 引用会失败?

最佳答案

std::set 值是不可变的,本质上是 const。此外,所有采用左值引用的成员函数都采用 const 引用。 const 值无法绑定(bind)到非 const 引用,并且您无法将常量引用参数传递给非常量比较函数参数。

关于c++ - 比较函数中按值传递、非常量引用与常量引用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38172032/

相关文章:

c++ - std::transform 包装器,带有指向成员函数和 back_inserter 的指针

typescript - Google 分析 : dataLayer. 推送不适用于变量数组?

python - 将文件路径从 Python 传递到 shell 脚本

java - 比较器java中计数器变量的奇怪输出

c++ - 在 C++ 中即时添加过滤功能

c++ - 不能在友元函数中使用重载运算符

java - 按匈牙利语字母顺序对匈牙利语字符串列表进行排序

java - 比较器排序

c++ - 为什么在非默认参数之前不允许使用默认参数?

动态调用带有可变参数的函数