[英]custom string sort comparison function weird behavior
我需要對字符串的向量進行排序,但是它不是海峽正向排序。 我編寫了一個自定義排序函數,該函數非常適合較小的矢量大小(<100個元素),但是對於較大的矢量,我的行為卻很奇怪。 注意:輸入的值都是數字。
我添加了一些debug printf語句來查看內部發生的情況,這就是我發現空字符串和其他奇怪的字符串正在傳遞到要排序的函數中的地方。
我的期望是僅將向量中的值傳遞到函數中。 我驗證了向量是否填充了已知值。
排序功能:
bool sortFunc( string a, string b ){
printf( "a: %s,\tb: %s \t", a.c_str(), b.c_str() );
//sorting magic defining 'bool retVal'
printf( "%s goes before %s\n", retVal?a.c_str():b.c_str(), retVal?b.c_str():a.c_str() );
return retVal;
}
主功能:
vector<string> a(n);
for( int i=0; i<n; ++i ){
cin >> a[i];
}
sort(a.begin(),a.end(),sortFunc);
奇怪的輸出示例:
a: 2, b: 10 2 goes before 10
a: 10, b: 10 10 goes before 10
a: , b: 10 goes before 10
a: , b: 10 goes before 10
a: \240E, b: 10 \240E goes before 10
a: , b: 10 goes before 10
a: {@, b: 10 {@ goes before 10
a: , b: 10 goes before 10
a: , b: 10 goes before 10
a: , b: 10 goes before 10
a: \225E, b: 10 10 goes before \225E
a: 2, b: 10 2 goes before 10
a: 10, b: \225E 10 goes before \225E
a: , b: goes before
a: , b: goes before
a: \245E, b: goes before \245E
a: \236E, b: \245E \245E goes before \236E
a: 0G\260\377, b: \236E 0G\260\377 goes before \236E
a: 0G\260\377, b: \245E 0G\260\377 goes before \245E
a: 0G\260\377, b: 0G\260\377 goes before
當std::sort
表現有趣時,幾乎總是因為無效的比較功能。 傳遞給std::sort
的比較函數必須提供嚴格的弱排序 。 通常的失敗是定義了比較函數,使得對於兩個對象a
和b
, compare(a,b)
返回true , compare(b,a)
返回true,即a
在b
之前, b
在a
之前。 發生這種情況時,排序算法很可能會耗盡數據的末端,並執行各種瘋狂的事情。
該問題的實際答案在其中:
//sorting magic defining 'bool retVal'
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.