C++学习笔记--STL标准模板库的认识与使用--关联式容器--遍历容器

可以利用迭代器来遍历关联式容器的所有元素。

set<int> s;
typedef set<int>::iterator si;
for (si it = s.begin(); it != s.end(); it++) cout << *it << endl;

需要注意的是,对 map 的迭代器解引用后,得到的是类型为 pair<Key, T> 的键值对。

在 C++11 中,使用范围 for 循环会让代码简洁很多:

set<int> s;
for (auto x : s) cout << x << endl;

对于任意关联式容器,使用迭代器遍历容器的时间复杂度均为O(n) 。

猜你喜欢

转载自blog.csdn.net/qq_51701007/article/details/121278166