std::for_each(listintegers.begin(), listintegers.begin(), Print); // 第二參數錯誤
for_each 範圍為 [first, last),次參數應為 end() 指向「最後一個元素之後」的迭代器。傳入 begin() 導致範圍為空,回調函式 Print 從未被呼叫。
#include <iostream>
#include <list>
#include <algorithm>
using namespace std;
void Print(int &item) { cout << item << " "; }
int main() {
list<int> lst;
lst.push_front(5);
lst.push_front(3);
lst.push_back(6); // list: 3, 5, 6
// 正確:begin() 到 end()
for_each(lst.begin(), lst.end(), Print); // 輸出: 3 5 6
cout << endl;
// C++11 range-based for 更簡潔
for (auto &x : lst) cout << x << ' ';
return 0;
}
for_each(lst.begin(), lst.end(), [](int &n){ cout << n << ' '; });
| 錯誤呼叫 | 結果 |
|---|---|
for_each(v.begin(), v.begin(), f) | 空範圍,無輸出 |
for_each(v.end(), v.end(), f) | 空範圍,無輸出 |
for_each(v.rbegin(), v.rend(), f) | 反向遍歷 |
for (auto &x : container)) 簡潔且不易出錯。std::for_each、std::transform 等,確保迭代器範圍正確。list 不支援隨機存取,僅雙向迭代器,無法用 v.begin() + n。