在c++中使用冒泡排序/交换对字符串进行排序
Using bubble sort/swap to sort strings in c++
我对C++很陌生,似乎无法解决这个问题。这个代码只是让用户输入一个动物列表(不超过25只动物,30个字母长),然后它会按照输入的顺序和字母顺序输出它们(使用气泡排序)。如果我的代码难以理解,我深表歉意。
每当我放入"狗"、"猫"、"鱼"等动物并用句点终止列表时,我通常会得到"CharacterStrings.exe中0x55b6d2f3处的未处理异常:0xC0000005:读取位置0xcccccccc的访问冲突。"但其他时候我会得到"CharacterStringsList.exe中发生缓冲区溢出,已损坏程序的内部状态。"
我只是很困惑如何解决这个问题。我试着用谷歌搜索这两个代码,但似乎找不到任何适合我的解决方案(因为我还是一个初学者,不知道如何做很多更高级的代码)。我很确定这个错误在我的交换函数中(也许?),但我看不出来。也许是逻辑错误?我想的都试过了。
如果你有什么问题,请告诉我。如有任何帮助或建议,我们将不胜感激!提前感谢:)
#include <iostream>
#include <iomanip>
#include <cstring>
using namespace std;
void getInput(char animals[][30]);
void outputLists(char animals[][30]);
void bubbleSort(char animals[][30], int n);
void Swap(char *a, char *b);
void getInput(char animals[][30])
{
cout << "Please enter a list of animals, terminated by a period: " << endl;
for(int i = 0; i < 25; i++)
{
cin >> animals[i];
if(strcmp(animals[i], ".") == 0)
break;
}
}
void bubbleSort(char animals[][30], int size)
{
for(int i = 0; i < size-1; i++)
for(int j = 0; j < size-1; j++)
if(animals[j] < animals[j+1])
Swap(animals[j], animals[j+1]);
}
void Swap(char *a, char *b)
{
char t[30];
strcpy(t, a);
strcpy(a, b);
strcpy(b, t);
}
void outputLists(char animals[][30])
{
//Output original list
for(int i = 0; i < 25; i++)
{
if(strcmp(animals[i], ".") == 0)
break;
cout << animals[i] << endl;
}
//Output sorted list
for(int i = 0; i < 25; i++)
cout << animals[i] << endl;
}
int main()
{
char animals[25][30];
getInput(animals);
cout << endl;
bubbleSort(animals,25);
outputLists(animals);
cout << endl;
system("pause");
return 0;
}
使用strcmp(s1, s2)
比较C样式字符串。如果s1小于s2,则返回一个小于零的值。
还有一个提示:C样式字符串是以null结尾的字符串(即字符串本身后面有一个零值),因此您需要一个大小至少为n+1的数组来存储长度为n的字符串。在您的情况下,30是不够的,但31是。
相关文章:
- 对字符串进行排序时,在c++中处理sort()
- 使用自定义比较函数使用std::sort()对矢量字符串进行排序时出现问题
- 在 c++ 中对类中的 c 字符串动态数组进行排序的最佳方法是什么?
- 按字母顺序对字符串中的字母进行排序,而无需使用内置的 sort()
- 字符串上的合并排序上的 Seg 错误
- 将图形表示为unordered_map<字符串、向量>时拓扑排序错误<string>
- 如何在数组 c++ 中对字符串进行排序
- 提高从排序字符串中获取字母顺序的顺序复杂性
- 尝试使用C++中的模板进行BST排序,但在使用随机字符串进行测试时不起作用
- 如何根据第二列/第三列等对字符串向量进行排序?
- 如何对向量进行排序<浮点数,字符串>而不考虑字符串
- C ++中的字符串排序,也没有在第5个元素正确排序
- C++:使用 LSD 基数排序字符串排序崩溃
- C 样式的字符串排序与排序和 qsort
- 自定义字符串排序
- 编号和字符串排序Al
- 使用STL对子字符串排序
- 如何在c++中按字母顺序对标准输入字符串排序
- c++向量字符串排序不工作
- SQLite 的不区分大小写的 UTF-8 字符串排序规则 (C/C++)