繁体   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