iterator迭代器

Many functions in the C++ standard library operate with iterators. An iterator is a variable that points to an element in a data structure. 用 iterator 来写遍历,遍历不同的容器,都可以用 iterator,但是只有部分容器支持下标访问,比如 vector。

  1. //set的遍历
  2. set<int>::iterator it;
  3. for (it = s.begin(); it != s.end(); it++) {
  4. cout << *it << "\n";
  5. }
  6. //输出最大元素
  7. it = s.end(); it--;
  8. cout << *it << "\n";
  9. //查找元素是否存在
  10. it = s.find(x);
  11. if (it == s.end()) {
  12. //x is not found
  13. }
  1. //示例
  2. //set<pair<int, int> >
  3. //不能写成set<pair<int, int>>,这也是不建议用#define宏定义的原因
  4. #include <bits/stdc++.h>
  5. using namespace std;
  6. typedef pair<int, int> PII;
  7. set<PII> s;
  8. int main()
  9. {
  10. s.insert(make_pair(3, 5));
  11. s.insert(make_pair(7, 9));
  12. s.insert(make_pair(11, 13));
  13. set<PII>::iterator it;
  14. for (it = s.begin(); it != s.end(); it++)
  15. printf("%d %d\n", (*it).first, (*it).second);
  16. return 0;
  17. }