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