【问题标题】:Why is my change to a range-for loop not work?为什么我对 range-for 循环的更改不起作用?
【发布时间】: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&lt; nums.size()-1; i++ )for (int i : nums ) 是等价的吗?前者迭代索引,而后者迭代nums的条目。
  • 还要注意for (int i = 0; i&lt; nums.size()-1; i++ ) 会跳过nums 中的最后一个条目,而for (int i : nums ) 包含最后一个条目。如果不使用更严格的范围,您将无法跳过 range-for 循环中的条目

标签: c++ for-loop c++11 foreach


【解决方案1】:

您的外部循环将i 设置为您的nums 向量中的实际值,但您的内部循环正在使用它,就好像它是一个索引一样!作为一个明确的示例,在您的外循环的第一次迭代中,i 将是 2,因此您的内循环将从 x : 3 开始。

由于您实际上对将索引作为计算的一部分感兴趣,因此使用传统风格的 for 循环可能最有意义。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2014-07-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-08-19
    • 2013-12-13
    • 1970-01-01
    相关资源
    最近更新 更多