0

这就是我正在做的,基本上是对动态生成的C-Strings数组进行排序,它将是“abc”的组合,为简洁起见长度小于5。令人困惑/有趣的是如何配置比较函数,这样它就不会按内存地址比较 C 字符串

srand ( time(NULL) );
char alpha[] = "abc";
char** CString = new char*[either 5 or 1000];
unsigned int j=0;
for (unsigned int i=0; i<either 5 or 1000;i++) {
    int ran = rand() % 5 + 2;
    CString[i] = new char[ran];
    for(j=0;j<ran-1;j++){
        CString[i][j] = alpha[rand() % (sizeof(alpha) - 1)];
    }
    CString[i][ran-1] = '\0';
}

std::sort(CString,CString+either 5 or 1000,SortCompare);

for(int i=0;i<5;i++){
    std::cout << *(CString+i) << " at " << CString+i << std::endl;
}

现在我有比较功能的三种配置

int SortCompare(char* a,  char* b){
    //return a<b;
    //return *a<*b;
    //return strcmp(a,b);
}

打印输出是

return strcmp(a,b):
CRASHED! //bummed because I had high hope for this

return a<b:
(when 5 C-strings):                        (when 1000 C-strings):
abba at 001F3248                           cbccb at 00544388 
bcb at 001F324C                            caac at 0054438C
cbb at 001F3250                            bcbc at 00544390
c at 001F3254                              ac at 00544394
ca at 001F3258                             a at 00544398
//conclusion: it's sorted by addresses. so turning head to the other one

return *a<*b:
(when 5 C-strings):                        (when 1000 C-strings):
abba at 001F3248                           cbccb at 00544388
bcb at 001F324C                            caac at 0054438C
cbb at 001F3250                            bcbc at 00544390
c at 001F3254                              ac at 00544394
ca at 001F3258                             a at 00544398
//I assumed it's value-sorted              //seriously hurt, belief has been destroyed seeing the memory addresses line up so neatly

因此,哪一个是按值排序的正确版本?或者我完全走错了路。需要救生员!谢谢

4

1 回答 1

3

如果您从来没有任何 NULL 指针:

bool SortCompare(char const* const a, char const* const b)
{
    return std::strcmp(a, b) < 0;
}

如果你确实有 NULL 指针,它只是稍微冗长一些:

bool SortCompare(char const* const a, char const* const b)
{
    return a && (!b || std::strcmp(a, b) < 0);
}
于 2012-09-25T00:35:47.217 回答