C++ 標準庫中 std::deque 的迭代器使用是基礎技能。雖然範圍 for(for (auto& x : deque))更簡潔,但理解傳統迭代器寫法對於閱讀舊代碼、調試及特定場景(如需要迭代器操作)至關重要。
#include <deque>
#include <iostream>
int main() {
std::deque<int> listed = {1, 2, 3, 4, 5};
// 正確聲明迭代器類型
std::deque<int>::iterator it = listed.begin();
// 標準 for 循環結構
for (; it != listed.end(); ++it) {
std::cout << *it << ' ';
}
std::cout << std::endl;
return 0;
}
std::deque<T>::iterator(或 auto it = listed.begin()),不可省略模板參數。listed.begin() 返回指向首元素的迭代器,注意是 函數調用,需加括號。it != listed.end(),end() 返回尾後迭代器,不可解引用。++it,避免後置遞增產生臨時對象開銷。*it 訪問元素值。| 錯誤代碼 | 問題 | 修正 |
|---|---|---|
deque::iterator it = listed.begin; | 缺少括號,begin 是成員函數 | listed.begin() |
for (it = listed.begin(); it != listed.end(); it++) | 使用後置遞增,有微小性能損耗 | ++it |
for (auto it = listed.begin(); it < listed.end(); ++it) | 迭代器不支持 < 比較(僅隨機訪問迭代器支持) | != 比較 |
在循環中 listed.erase(it) 後繼續 ++it | 迭代器失效,導致未定義行為 | it = listed.erase(it) 獲取新迭代器 |
// 反向遍歷
for (auto rit = listed.rbegin(); rit != listed.rend(); ++rit) {
std::cout << *rit << ' ';
}
// 僅讀遍歷,防止誤修改
for (auto cit = listed.cbegin(); cit != listed.cend(); ++cit) {
// *cit = 10; // 編譯錯誤
std::cout << *cit << ' ';
}
掌握 deque 迭代器的標準 for 循環寫法,關鍵在於:正確聲明類型、調用 begin()/end()、使用 != 比較、前置遞增、解引用訪問。這不僅適用於 deque,也是所有 STL 容器迭代器遍歷的通用模式。