使用 "constant" 的 C++ 函数重载
C++ function overloading with "constant"
我一直在编写图算法,我想出了这个问题。在 C++11 中
我尝试创建如下结构,
struct edges{
int u , v , w ;
edges(){}
edges( int _u , int _v , int _w ) {
u = _u , v = _v , w = _w ;
}
bool operator < ( edges & r ) {
return w < r.w ;
}
};
所以,我写了这段代码,编译成功。
但是当我像下面这样调用 std::sort() 函数时,
sort( arr , arr + M ) ; // here arr is an array of edges with M elements
然后我得到指向 stl_algo.h 行号 2242 的编译错误。我正在添加来自 stl_algo.h、
的代码部分
/// This is a helper function...
template<typename _RandomAccessIterator, typename _Tp>
_RandomAccessIterator
__unguarded_partition(_RandomAccessIterator __first,
_RandomAccessIterator __last, const _Tp& __pivot)
{
while (true)
{
while (*__first < __pivot) // 2242 number line
++__first;
--__last;
while (__pivot < *__last)
--__last;
if (!(__first < __last))
return __first;
std::iter_swap(__first, __last);
++__first;
}
}
于是在网上找了解决办法,得到了一个。我必须用 const 关键字重载运算符,如下所示,
struct edges{
int u , v , w ;
edges(){}
edges( int _u , int _v , int _w ) {
u = _u , v = _v , w = _w ;
}
bool operator < ( const edges & r ) const {
return w < r.w ;
}
};
我的问题是,如果我调用 std::sort() 函数,为什么我会用 'const' 关键字重载运算符?
运算符<用于比较两个对象,参数传递的对象不会改变,所以参数必须是 const。
我一直在编写图算法,我想出了这个问题。在 C++11 中 我尝试创建如下结构,
struct edges{
int u , v , w ;
edges(){}
edges( int _u , int _v , int _w ) {
u = _u , v = _v , w = _w ;
}
bool operator < ( edges & r ) {
return w < r.w ;
}
};
所以,我写了这段代码,编译成功。 但是当我像下面这样调用 std::sort() 函数时,
sort( arr , arr + M ) ; // here arr is an array of edges with M elements
然后我得到指向 stl_algo.h 行号 2242 的编译错误。我正在添加来自 stl_algo.h、
的代码部分/// This is a helper function...
template<typename _RandomAccessIterator, typename _Tp>
_RandomAccessIterator
__unguarded_partition(_RandomAccessIterator __first,
_RandomAccessIterator __last, const _Tp& __pivot)
{
while (true)
{
while (*__first < __pivot) // 2242 number line
++__first;
--__last;
while (__pivot < *__last)
--__last;
if (!(__first < __last))
return __first;
std::iter_swap(__first, __last);
++__first;
}
}
于是在网上找了解决办法,得到了一个。我必须用 const 关键字重载运算符,如下所示,
struct edges{
int u , v , w ;
edges(){}
edges( int _u , int _v , int _w ) {
u = _u , v = _v , w = _w ;
}
bool operator < ( const edges & r ) const {
return w < r.w ;
}
};
我的问题是,如果我调用 std::sort() 函数,为什么我会用 'const' 关键字重载运算符?
运算符<用于比较两个对象,参数传递的对象不会改变,所以参数必须是 const。