for (auto x : nums)

Posted lihello

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了for (auto x : nums)相关的知识,希望对你有一定的参考价值。

class Solution 
public:
    int findDuplicate(vector<int>& nums) 
        int n = nums.size() - 1;
        int l = 1, r = n;
        while (l < r)
            int mid = l + r >> 1;
            int cnt = 0;
            for (auto x : nums)
                if (x >= l && x <= mid)
                    cnt++;
            if (cnt > mid - l + 1) r = mid;
            else l = mid + 1;
        
        return r;
    
;

上述代码中
for (auto x : nums)
作用就是迭代容器中所有的元素,每一个元素的临时名字就是x,等同于下边代码
for (vector<int>::iterator iter = nums.begin(); iter != nums.end(); iter++)

以上是关于for (auto x : nums)的主要内容,如果未能解决你的问题,请参考以下文章