问题遇到的现象和发生背景
这个是在刷leetcode题中遇到的c++语法问题,在strStr函数的for循环中,i <= (haystack.length() - needle.length())应该一次循环都不执行才符合逻辑。
但却执行了haystack.length()次。请问内部是什么原因呢?
问题相关代码,请勿粘贴截图
#include<string>
#include<iostream>
using namespace std;
int strStr(string haystack, string needle) {
if(needle.length() == 0) return 0;
int n = haystack.length() - needle.length();
// cout << n << endl;
for(int i = 0; i <= (haystack.length() - needle.length()); i++)
{
cout << i << endl;
if(haystack.substr(i, needle.length()) == needle)
return i;
}
return -1;
}
int main()
{
string a = "aaaaa";
string b = "aaaaaaaaaaa";
strStr(a, b);
return 0;
}
运行结果及报错内容
0
1
2
3
4
5
6
terminate called after throwing an instance of 'std::out_of_range'
what(): basic_string::substr: __pos (which is 6) > this->size() (which is 5)