谁能在 STL 的上下文中解释这种行为 sort
算法?
如果operator <
未定义 const
它给出了错误,
error: passing ‘const B’ as ‘this’ argument of ‘bool B::operator<(const B&)’ discards qualifiers [-fpermissive]
while (__pivot < *__last)
是sort
算法 lhs const
对象或 sort
是const
方法?
class B
{
public:
...
bool operator < (const B& b) const // why const required here?
{
return (m_i < b.m_i);
}
...
private:
int m_i;
int m_j;
};
int main()
{
vector<B> Bvec2 {B(5), B(3), B(30), B(20), B(8)};
std::sort(Bvec2.begin(), Bvec2.end());
...
}
最佳答案
将函数标记为 const promise 它不会更改对象。所以它可以用在 const 对象上。
STL 几乎肯定会将参数作为 const,因为这是明智之举。
定义operator<
不会对您造成伤害作为 const 因为我无法想象有一个小于运算符来改变对象。那将是愚蠢的。
如果您想知道在 Fedora 20 机器上从 libstdc++ bits/STL_algo.h 复制的代码的确切位置:
/// This is a helper function...
template<typename _RandomAccessIterator, typename _Tp, typename _Compare>
_RandomAccessIterator
__unguarded_partition(_RandomAccessIterator __first,
_RandomAccessIterator __last,
const _Tp& __pivot, _Compare __comp)
const _Tp& __pivot
, 就在那里。
关于c++ - 为什么重载的 ' operator < ' 应该是类的常量?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23927003/