对混合(空和非空)cstrings数组进行排序

Sort an array of mixed (empty and non-empty) cstrings

本文关键字:数组 排序 cstrings 混合      更新时间:2023-10-16

我试图将空的(example[0] == '')c字符串放在数组的后面,而不是前面,同时保持升序。我使用strcmp(...)使用简单的选择排序将当前cstring与数组中的下一个cstring进行比较,但我希望能够将其应用于其他类型的排序以及

edit——在我的代码中,tempword实际上是一个对象,而不是char*,但这在功能上应该是等效的

sortList() {
   char *tempword = new char[30];
   int min;
   for (int i=0; i<(d_length-1); ++i) {
      min = i;
      for (int j=i+1; j<d_length; ++j) {
         if ((strcmp(d_wordlist[min], d_wordlist[j]) > 0)) {
         min = j;
         }
      }
      if (min != i) {
         *tempword = d_wordlist[min];
         d_wordlist[min] = d_wordlist[i];
         d_wordlist[i] = *tempword;
      }
   }
   delete[] tempword;
}

*edit 2——我最终按照"我很困惑"的建议为strcmp制作了一个包装器函数。

int compare(const char* str1, const char* str2) {
   if (str2[0] == '')
      return -1;
   return strcmp(str1, str2);
}

直接的方法是让sortList函数采用自定义比较函数。如果左操作数是空字符串"",则自定义比较函数应返回false。如果左操作数不为空,但右操作数为空,则返回true。否则,只需进行常规字符串比较。

例如,使用std::string,这个比较函数应该可以完成以下操作:

bool comp(const std::string &lhs, const std::string &rhs)
{
  if (lhs == "") return false;
  return rhs == "" || !(rhs < lhs);
}

请注意,您需要将sortList修改为交换单词而不是字母,以获得您想要的内容。