簡體   English   中英

自定義字符串排序比較功能怪異行為

[英]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的比較函數必須提供嚴格的弱排序 通常的失敗是定義了比較函數,使得對於兩個對象abcompare(a,b)返回true compare(b,a)返回true,即ab之前, ba之前。 發生這種情況時,排序算法很可能會耗盡數據的末端,並執行各種瘋狂的事情。

該問題的實際答案在其中:

//sorting magic defining 'bool retVal'

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM