C++ 比较函数中的传递值与非常量引用与常量引用
为什么在C++ 比较函数中的传递值与非常量引用与常量引用,c++,arguments,comparator,C++,Arguments,Comparator,为什么在std::set中传递非const引用失败 std::set值是不可变的,本质上是常量。此外,采用l值引用的所有成员函数均采用constreferenceconst值不能绑定到非const引用,并且不能将常量引用参数传递给非const比较函数参数。“但它会报告错误”-您应该将其包括在问题帖子中,正如内容可能描述的那样(尽管对于初学者来说有些神秘)究竟出了什么问题std::set将常量引用发送到比较器,如果比较器需要非常量引用,则此操作将不起作用。您可以向请求不可变引用的函数发送可变引用;
std::set
中传递非const
引用失败 std::set
值是不可变的,本质上是常量。此外,采用l值引用的所有成员函数均采用const
referenceconst
值不能绑定到非const
引用,并且不能将常量引用参数传递给非const比较函数参数。“但它会报告错误”-您应该将其包括在问题帖子中,正如内容可能描述的那样(尽管对于初学者来说有些神秘)究竟出了什么问题std::set
将常量引用发送到比较器,如果比较器需要非常量引用,则此操作将不起作用。您可以向请求不可变引用的函数发送可变引用;事实并非如此。我添加了错误报告,谢谢!
/**
* 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;
};
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]’