C++ 字符串下标超出范围

c++ string subscript out of range

本文关键字:范围 下标 字符串 C++      更新时间:2023-10-16

请帮助调试。它给了我一个错误"字符串下标超出范围错误"。

程序需要使用插入排序算法对文本进行排序。

这是代码:

#include<iostream>
#include<string>
using namespace std;
void insertionSort(string &text, int size) {
  char temp;
  int i;
  for(int j=1;j<size;j++)
  {
    //text.push_back(temp);
    temp=text[j];
    i=j-1;
   while(i>=0 && text[i]>temp)
 {
 text[i+1]=text[i];
  i--;
 }
    text[i+1]=temp;
  }
}
int main()
{
  string text="this a just text need to be sorted";
  int size = text.length();
  insertionSort(text,size);
  cout<<text<<endl;
  return 0;
}

调试断言失败!

行:1441:

表达式:字符串下标超出范围

我应该把text[i+1]=text[j]改成text[i+1]=text[i];

替换

while(text[i]>temp && i>=0)

while(i>=0 && text[i]>temp)

原因:

当 i 变为负数时,即 i == -1 ,然后首先检查i>=0而不是检查text[i]>temp(它试图访问位置 -1 处的数组元素并超出范围)。

编辑:

同时替换

text[i+1]=text[j];

text[i+1]=text[i];

为什么会这样? :在插入排序中,如果我们在下部有大于文本[j]的条目(即0到j-1),那么我们需要将这些条目向前推,并在不再有大于文本的元素[j]时停止。

您必须更改此指令:

text[i+1]=text[i];

j == 1你的 while 循环以 i==0 开头时,你在循环中递减i,然后在循环的下一次执行时检查text[i],这是无效的(i == -1在这里)

要修复,您需要先检查i的有效性:

while(i >=0 && text[i] > temp) {
  // ...
}

这样做是正确的,因为&&运算符有一个短路规则:如果第一个操作数(在本例中为i>=0)产生false,则表达式的其余部分(text[i] > temp)不被计算

您有关于问题的信息。解决此问题的简单方法是,放置一些 print 语句以了解与字符串数组一起使用的索引值。

另一个注释是,请不要传递字符串的长度,因为如果你在函数内部调用 text.length(); 在更改它之前可以获取字符串的长度。