gpt4 book ai didi

c++ - 如何在 C++ 中对字符串进行冒泡排序?

转载 作者:行者123 更新时间:2023-11-28 05:24:14 24 4
gpt4 key购买 nike

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

如何正确实现?我可能缺少一些简单的东西。谢谢。

enter image description here

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

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;
}

最佳答案

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

#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

关于c++ - 如何在 C++ 中对字符串进行冒泡排序?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40876572/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com