【发布时间】:2014-09-18 20:30:52
【问题描述】:
在做课堂作业时,我遇到了这个问题(注意循环的条件)
// 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++;
}
}
//*/
为什么第一个有效,第二个无效?是关于操作顺序、bool 强制转换为 int、运算符关联性还是 OBOE?
【问题讨论】:
-
length()是否返回无符号类型? -
不应该是 k + cmets[i].length()
-
@cyan: 不,如果你从第一个循环条件的两边减去
negwords[i].length(),你会得到第二个。 -
请说明negwords和cmets的定义。
-
通过正确编译(例如,对于 gcc,您应该至少使用
-Wall编译(!)),失败的代码应该会警告您有关有符号和无符号整数之间的比较
标签: c++