简体   繁体   English

为什么我对 range-for 循环的更改不起作用?

[英]Why is my change to a range-for loop not work?

I'm at a loss.我不知所措。 I am trying to sum two numbers of vector such that they equal target, then return their indices;我试图将两个向量相加,使它们等于目标,然后返回它们的索引; however, when running the code with a C++11 for-loop, the result is incorrect.但是,当使用 C++11 for 循环运行代码时,结果不正确。 With vector [2,7,11,15] and target=9, the result for the C++11 loop is [0, 0].当向量 [2,7,11,15] 和 target=9 时,C++11 循环的结果是 [0, 0]。 Using the C-style loop, it is [0,1].使用 C 风格的循环,它是 [0,1]。 What gives?是什么赋予了?

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;  
    } 
};

Your outer loop is setting i to the actual value within your nums vector, but your inner loop is using it as if it's an index!您的外循环将i设置为您的nums向量中的实际值,但您的内循环正在使用它,就好像它是一个索引一样! As an explicit example, on the first iteration of your outer loop, i will be 2 and so your inner loop will start at x : 3 .作为一个明确的例子,在您的外循环的第一次迭代中, i将为2 ,因此您的内循环将从x : 3开始。

Since you're actually interested in the index as part of your calculations, it probably just makes the most sense to use the traditional-style for-loop.由于您实际上对作为计算一部分的索引感兴趣,因此使用传统样式的 for 循环可能最有意义。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM