#include<iostream> #include<vector> intmain(){ std::vector<int> v = {0, 1, 2, 3, 4, 5}; for (constint& i : v) // access by const reference std::cout << i << ' '; std::cout << '\n'; for (auto i : v) // access by value, the type of i is int std::cout << i << ' '; std::cout << '\n'; for (auto&& i : v) // access by forwarding reference, the type of i is int& std::cout << i << ' '; std::cout << '\n'; constauto& cv = v; for (auto&& i : cv) // access by f-d reference, the type of i is const int& std::cout << i << ' '; std::cout << '\n'; for (int n : {0, 1, 2, 3, 4, 5}) // the initializer may be a braced-init-list std::cout << n << ' '; std::cout << '\n'; int a[] = {0, 1, 2, 3, 4, 5}; for (int n : a) // the initializer may be an array std::cout << n << ' '; std::cout << '\n'; for (int n : a) std::cout << 1 << ' '; // the loop variable need not be used std::cout << '\n'; }
解
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
#include<iostream> #include<set> #include<vector>
usingnamespacestd;
intrepeatedNTimes(vector<int> &A) { set<int> m; for (vector<int>::iterator it = A.begin(); it != A.end(); it++) { if (m.find(*it) != m.end()) { return *it; } else { m.insert(*it); } } }
不过有个更好的做法,在LeetCode上看到的:
1 2 3 4 5 6 7 8 9 10 11 12
classSolution { public: intrepeatedNTimes(vector<int>& A){ unordered_set<int> seen; for (int a: A) { if (seen.count(a)) return a; seen.insert(a); } return0; } };