*, ->, ++, -- 等運算子。| 類別 | 支援操作 | 典型容器 |
|---|---|---|
| Input Iterator | *p, ++ | istream_iterator |
| Output Iterator | *p = val, ++ | ostream_iterator |
| Forward Iterator | Input + Output, 單向遍歷 | forward_list |
| Bidirectional Iterator | Forward + -- | list, set, map |
| Random Access Iterator | Bidirectional + +n, -n, [] | vector, deque, string |
能力遞增:Input/Output → Forward → Bidirectional → Random Access。
begin(), end(), rbegin(), rend()size(), empty(), max_size()insert(), erase(), clear(), swap()push_back(), pop_back(), front(), back(), resize(), reserve()(vector/string)find(), count(), lower_bound(), upper_bound(), equal_range()// 簡化版 templateclass _Vector_const_iterator { typedef T* pointer; pointer _Myptr; // 內部就是原始指標 public: T& operator*() const { return *_Myptr; } _Vector_const_iterator& operator++() { ++_Myptr; return *this; } // ... }; template class _Vector_iterator : public _Vector_const_iterator { // 繼承 const 版本,operator* 回傳 non-const reference }; typedef _Vector_iterator iterator; typedef reverse_iterator reverse_iterator; // 適配器包裝
迭代器本質是包裝原始指標的智慧指標;reverse_iterator 以適配器模式包裝正向迭代器實現反向遍歷。
push_back:若觸發擴容(capacity 變化),**所有**迭代器失效;否則僅 end() 失效。insert/erase:插入/刪除點及其後所有迭代器失效。// 正確:使用 insert/erase 返回的新迭代器
iter = vec.insert(iter, val);
iter = vec.erase(iter);
// 錯誤:迭代器失效後繼續使用
for (auto it = v.begin(); it != v.end(); ++it) {
if (cond) v.erase(it); // UB!
}
原則:修改容器結構後,重新獲取迭代器或使用返回值。