这就是我正在做的,基本上是对一个动态生成的C-String数组进行排序,它将是"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因此,哪一个版本是按值排序的正确版本?或者我完全走错了路。需要一个救生员!谢谢
发布于 2012-09-25 08:35:47
如果你从来没有任何空指针:
bool SortCompare(char const* const a, char const* const b)
{
return std::strcmp(a, b) < 0;
}如果你有空指针,它只会稍微冗长一点:
bool SortCompare(char const* const a, char const* const b)
{
return a && (!b || std::strcmp(a, b) < 0);
}https://stackoverflow.com/questions/12574729
复制相似问题