今天在写kmp算法的时候遇到一个很神奇的现象
代码如下:
#include <iostream>
using namespace std;
int main(){
string needle = "ll";
int needle_length = needle.length();
cout<<"(-1 < (needle.length())) "<<(-1 < (needle.length()))<<endl;
cout<<"(-1 < needle_length) "<<(-1 < needle_length)<<endl;
return 0;
}
输出是:
(-1 < (needle.length())) 0
(-1 < needle_length) 1
后来上网搜索得知str.length()返回的是unsigned int类型,与int比较会得不到预期的结果,需要强制转化为int才能得到正确的结果.