在完成一项班级作业时,我遇到了这个问题(请注意循环条件)
// This one works.
for (int k = 0; k + negwords[j].length() < comments[i].length(); k++) {
if (comments[i].substr(k, negwords[j].length()) == negwords[j]) {
negativeScore++;
}
}
//*/
/*/ This one doesn't: It fails with an out-of-bounds index.
for (int k = 0; k < comments[i].length() - negwords[j].length(); k++) {
if (comments[i].substr(k, negwords[j].length()) == negwords[j]) {
negativeScore++;
}
}
//*/
为什么第一个有效而第二个无效?是关于操作顺序、布尔型强制转换为整数、运算符结合性还是OBOE的问题?
length()
函数返回的是一个无符号类型吗? - Ben Voigtnegwords[i].length()
,你就得到了第二个条件。 - Ben Voigt-Wall
来编译gcc),失败的代码应该会给您一个有关有符号和无符号整数之间比较的警告。 - Hagen von Eitzen