在c++中使用冒泡排序/交换对字符串进行排序

Using bubble sort/swap to sort strings in c++

本文关键字:字符串 排序 交换 c++ 冒泡排序      更新时间:2023-10-16

我对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是。