C++ 字符串下标超出范围
c++ string subscript out of range
请帮助调试。它给了我一个错误"字符串下标超出范围错误"。
程序需要使用插入排序算法对文本进行排序。
这是代码:
#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(); 在更改它之前可以获取字符串的长度。
相关文章:
- 尝试通过多个向量访问变量时,向量下标超出范围
- 矢量下标超出SFML游戏中的范围
- 运行时错误:矢量下标超出范围:正在检查空集
- 如果变量数据包含大于 vector 所有元素的整数,则仅在视觉工作室上接收"矢量下标超出范围"?
- 编译期间矢量下标超出范围
- C++ 调试断言失败 - 矢量下标超出视觉工作室的范围
- 对矢量来说是全新的.矢量下标超出范围
- C++十进制到十六进制(字符串下标超出范围)
- 创建结构体向量,表达式:向量下标超出范围
- 读取矢量时矢量下标超出范围
- 断言失败错误,C++中的矢量下标超出范围问题
- 如何在 Linux 上强制执行矢量下标超出范围的调试断言
- 表达式:矢量下标超出范围
- 矢量下标超出范围,带有嵌套的 for 循环
- 向量下标超出向量向量的范围
- gcc8.2如何启用警告:数组下标在数组范围之上[-warray-bounds]
- 向量下标出的范围错误.即使向量的索引大于访问数据的索引,也会发生误差
- std::vector<std::vector<int>>:调试断言失败。C++矢量下标超出范围保留内存
- 重命名两个目录中的文件名,如果它们之间的某些字符匹配 - 矢量下标超出范围
- 行进立方体重建 - 向量下标超出范围