【问题标题】:How to do bubblesort with strings in c++?如何在 C++ 中对字符串进行冒泡排序?
【发布时间】:2017-04-14 01:55:25
【问题描述】:

我是 C++ 新手,我必须使用冒泡排序使字符串按升序显示。我有一个包含各种字符串的数据文件。我将这些值存储到一个数组中。当我尝试使用课本中的冒泡排序代码时,单词的排序方式是这样的。

我怎样才能正确地实现它?我想念的可能很简单。谢谢。

我不知道为什么会这样,但这是我用于冒泡排序的代码。

void sortListWords(string list[], int count) {
  int temp;
  for (int i = 0; i < count - 1; i++)
    for (int j = 0; j < count - (i + 1); j++)
      if (list[j] > list[j + 1]) {
        temp = list[j];
        list[j] = list[j + 1];
        list[j + 1] = temp;
      }
   }

int main(){
  // call sorting function
  // words are loaded from data file
  sortListWords(wordListing, size);

  // print array to screen
  for(int i=0; i<size; i++)
    cout << wordListing[i];

   return 0;
}

【问题讨论】:

  • 您希望它们按字典顺序排序吗?另请说明您在哪里定义size
  • 我看不出这将如何编译,因为您正在使用 int 临时变量来交换 std::string 值。
  • 它实际上与整数的冒泡排序代码相同。你能编写代码对整数数组进行冒泡排序吗?如果是这样,唯一的区别就是使用的类型——其他一切都保持不变。
  • @JackRyan 是的。 size 是一个叫做 size 的常量,它等于 20。
  • @FredLarson 我刚刚注意到了。我书中的例子是使用数组中的整数,所以是的,除非它是一个字符串,否则它不会编译。

标签: c++ arrays string bubble-sort


【解决方案1】:

只是对您的示例进行了最小的更改。请将其与您所拥有的进行比较,您应该会看到问题出在哪里:

#include <string>
#include <iostream>

void sortListWords(std::string list[], int count) {
  std::string temp;
  for (int i = 0; i < count - 1; i++) {
    for (int j = 0; j < count - (i + 1); j++) {
      if (list[j] > list[j + 1]) {
        temp = list[j];
        list[j] = list[j + 1];
        list[j + 1] = temp;
      }
    }
  }
}

int main(){
  const int size = 4; 
  std::string wordListing[] = {"Hello", "World", "Fred", "John" };    

  // call sorting function
  // words are loaded from data file
  sortListWords(wordListing, size);

  // print array to screen
  for(int i=0; i<size; i++) {
    std::cout << wordListing[i] << '\n';
  }
  return 0;
}

我特别做的是将temp 的类型从int 交换为std::string。我还在 for 循环的主体周围添加了大括号以提高可读性。

最后我将前两行添加到您的main 函数中(用于测试):

  const int size = 4; 
  std::string wordListing[] = {"Hello", "World", "Fred", "John" };

输出是:

Fred
Hello
John
World

【讨论】:

    【解决方案2】:

    将此int temp; 更改为string temp;

    【讨论】:

    • 你真的应该使用 std::string
    • 我假设提问者正在使用 std 命名空间。谢谢
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2015-04-17
    • 1970-01-01
    • 2014-05-09
    • 2018-09-22
    • 1970-01-01
    • 2016-02-09
    • 2014-08-05
    相关资源
    最近更新 更多