首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> 更多程式語言 >> 程式設計綜合問答

STL for_each 遍歷 list:參數錯誤導致無輸出

     編輯:程式設計綜合問答

錯誤程式碼

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;
}

補充:lambda 表達式 (C++11)

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)反向遍歷

最佳實務

  • 優先使用 range-based for (for (auto &x : container)) 簡潔且不易出錯。
  • 需算法組合時使用 std::for_each、std::transform 等,確保迭代器範圍正確。
  • list 不支援隨機存取,僅雙向迭代器,無法用 v.begin() + n。
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved