std::sort 在 VC2010 出错
在调试某程序时发现如下警告信息:
Debug Assertion Failed!
File: c:\program files (x86)\microsoft visual studio
10.0\vc\include\algorithm
Line: 3657
Expression: invalid operator<
通过简单测试发现是vc 2010版本sort算法的问题。
对于元素大小相等的情况,如果自定义排序函数
对元素进行>=的比较时就会出错。
但相同情况在vc6.0调试不会出现问题。
希望有高手能解答。
bool GreatNumber(const int n1,const int n2)
{
return n1>=n2;//在vc 2010如果改成return n1>n2;则能成功通过,而vc6没这个问题
}
void CTestsortDlg::OnOK()
{
// TODO: Add extra validation here
int a[4]={1000,1000,1000,1000};
std::sort(a,a+4,GreatNumber);
CDialog::OnOK();
}
[解决办法]
引自
http://www.cplusplus.com/reference/algorithm/sort/
sort
function template
<algorithm>
template <class RandomAccessIterator>
void sort ( RandomAccessIterator first, RandomAccessIterator last );
template <class RandomAccessIterator, class Compare>
void sort ( RandomAccessIterator first, RandomAccessIterator last, Compare comp );
Sort elements in range
Sorts the elements in the range [first,last) into ascending order.
The elements are compared using operator< for the first version, and comp for the second.
Elements that would compare equal to each other are not guaranteed to keep their original relative order.
Parameters
first, last
Random-Access iterators to the initial and final positions of the sequence to be sorted. The range used is [first,last), which contains all the elements between first and last, including the element pointed by first but not the element pointed by last.
comp
Comparison function object that, taking two values of the same type than those contained in the range, returns true if the first argument goes before the second argument in the specific strict weak ordering it defines, and false otherwise.
请注意红色部分
[解决办法]
VS2010和VC6.0用到的STL不同了吧?具体的我忘了,原理我猜想是这样的:
a=1000;
b=1000;
VS2010里的STL是这样判断二者相等的,a>b假,b>a假,说明a==b;
如果按你给的比较函数,就会a>=b真,b>=a真,当然也说明了a==b,可是STL的源码里就认假假为真吧。
[解决办法]