【发布时间】:2021-12-05 00:30:29
【问题描述】:
我很茫然。我试图将两个向量相加,使它们等于目标,然后返回它们的索引;但是,当使用 C++11 for 循环运行代码时,结果不正确。对于向量 [2,7,11,15] 和 target=9,C++11 循环的结果是 [0, 0]。使用 C 风格的循环,它是 [0,1]。什么给了?
class Solution {
public:
vector<int> twoSumCstyle(vector<int>& nums, int target) {
vector<int> sol(2);
bool found = false;
for (int i = 0; i< nums.size()-1; i++ ){
for ( int x = i +1; x <nums.size(); x++){
if (nums[i] + nums[x] == target) {
sol[0] = i;
sol[1] = x;
found = true;
break;
}
}
if (found) break;
}
return sol;
}
vector<int> twoSumC11(vector<int>& nums, int target) {
vector<int> sol(2);
bool found = false;
for (int i : nums ){
for ( int x = i +1; x <nums.size(); x++){
if (nums[i] + nums[x] == target) {
sol[0] = i;
sol[1] = x;
found = true;
break;
}
}
if (found) break;
}
return sol;
}
};
【问题讨论】:
-
因为在
for (int i : nums)中,i将包含来自nums的值,而不是索引。 -
您认为
for (int i = 0; i< nums.size()-1; i++ )和for (int i : nums )是等价的吗?前者迭代索引,而后者迭代nums的条目。 -
还要注意
for (int i = 0; i< nums.size()-1; i++ )会跳过nums中的最后一个条目,而for (int i : nums )包含最后一个条目。如果不使用更严格的范围,您将无法跳过 range-for 循环中的条目
标签: c++ for-loop c++11 foreach