对于下面的代码片段,我使用了一个包含项目 {1, 2, 3} 的 vector ,我只想得到这些对的乘积之和,例如 (1*2) + ( 1*3) + (2*3) 即 11。
for(unsigned i = {0}; i < vec.size(); ++i) {
for(unsigned j = i + 1; j < vec.size(); ++j) {
// ^^^^^^^
preresult = vec.at(i) * vec.at(j);
result += preresult;
}
}
问题是,当我在内部循环 j
中从 1 开始时,我的答案是 30,只有当我更改为 j = i + 1 时我才得到正确答案
。
谁能告诉我为什么? j = 1
不是很好吗?
最佳答案
只有3个值,所以我们可以在很短的时间内展开循环
从 j = 1
开始
result += vec.at(0) * vec.at(1); // 2
result += vec.at(0) * vec.at(2); // 3
result += vec.at(1) * vec.at(1); // 4 Oops: pairing 2 with itself
result += vec.at(1) * vec.at(2); // 6
result += vec.at(2) * vec.at(1); // 6 Oops: Seen already
result += vec.at(2) * vec.at(2); // 9 Oops: pairing 3 with itself
从 j = i + 1
开始
result += vec.at(0) * vec.at(1); // 2
result += vec.at(0) * vec.at(2); // 3
result += vec.at(1) * vec.at(2); // 6
关于c++ - 在嵌套 for 循环中从 j = i +1 vs j = 1 开始,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58846983/