这就是我正在做的事情,基本上是对一组动态生成的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
因此,哪一个是按值排序的正确版本?或者我完全走错了路。需要救生员!感谢
答案 0 :(得分: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);
}