【问题标题】:pass by value vs non-const reference vs const reference in comparison function比较函数中按值传递 vs 非常量引用 vs 常量引用
【发布时间】:2016-07-03 16:34:58
【问题描述】:
/**
 * 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 引用发送到您的比较器,如果比较器需要非常量引用,这将不起作用。您可以将可变引用发送到请求不可变引用的函数;相反的情况不是
  • 我添加了错误报告,谢谢!

标签: c++ arguments comparator


【解决方案1】:

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

【讨论】:

    猜你喜欢
    • 2011-06-09
    • 2014-03-03
    • 1970-01-01
    • 2011-01-19
    • 2014-07-24
    • 2020-07-06
    • 2013-08-01
    • 2013-07-12
    • 2014-09-14
    相关资源
    最近更新 更多