c++ - 按字母顺序排列的字符串

标签 c++ string sorting loops

我正在尝试使用递归函数按字母顺序打印字符串,但它给出了字符串下标超出范围的错误。

string alpha(string word)
{
    char temp;
    int count = 0;
    int i = 0;

    while (count < word.size())
    {
        if (word[i] > word[i + 1])
        {
            temp = word[i];
            word[i] = word[i + 1];
            word[i + 1] = temp;
            i++;
            if (i >= word.size())
            {
                alpha(word);
            }
        }
        else
        {
            count++;
        }
    }
    return word;
}

最佳答案

因为你使用 if (word[i] > word[i + 1]) 你必须在结束之前停止你的循环......并且你需要 counti(不是两者);也就是

while (i + 1 < word.size()) // <-- like so

或者你可以使用

int i = 1;
while (i < word.size()) {
  if (word[i - 1] > word[i]) {

关于c++ - 按字母顺序排列的字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25451470/

相关文章:

c++ - 实时应用程序中的内存泄漏检查

c++ - 亚马逊在线评估编码问题找到第n个几何级数

c - qsort比较字母顺序的字符串

c++ - 接受用户定义文字的排列时防止过载爆炸

c++ - 共享库中静态函数成员的销毁顺序

c++ - 带数组的字符串

c# - 将文件过滤器应用于文件名的字符串 [],而不打开 OpenFileDialog

python - 根据条件从字典列表中生成唯一的字典对

c++ - 固定大小的容器,其中元素已排序并可以提供指向 C++ 中数据的原始指针

c++ - 我可以在没有 main() 函数的情况下调试(逐步执行)代码吗?