for(auto a:b)与for(auto &a:b)的作用
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;
}
};
class Solution {
public:
int getMissingNumber(vector<int>& nums) {
int n = nums.size();
int sum = 0;
for(auto & x : nums) sum += x;
return n * (n + 1) / 2 - sum;
}
};
for(auto a:b)中b为一个容器,效果是利用a遍历并获得b容器中的每一个值,但是a无法影响到b容器中的元素。
for(auto &a:b)中加了引用符号,可以对容器中的内容进行赋值,即可通过对a赋值来做到容器b的内容填充。