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

C++ partition 算法報錯:迭代器類型不匹配解決方案

     編輯:程式設計綜合問答

錯誤現象

代碼調用 std::partition 時編譯報錯:
沒有找到接受……類型的左操作數的運算符(或沒有可接受的轉換)

問題代碼

vector<string> vec{ "strings", "helloworld", "zay", "uah", "kakaka" };
auto it = partition(vec.cbegin(), vec.cend(), func); // 錯誤行
auto begin = vec.begin();
while (begin != it)
{
    cout << *begin << endl;
    ++begin;
}

原因分析

  • vec.cbegin() 返回 const_iterator(只讀迭代器)。
  • std::partition 需要 可寫迭代器(iterator),因為它會交換元素位置。
  • 將 const_iterator 傳給需要修改容器的算法導致類型不匹配。

修正代碼

// 將 cbegin()/cend() 改為 begin()/end()
auto it = partition(vec.begin(), vec.end(), func);
// 其餘代碼不變

補充:C++11 迭代器類型速查

函數返回類型可修改元素
begin()iterator是
end()iterator是
cbegin()const_iterator否
cend()const_iterator否
rbegin()reverse_iterator是
crbegin()const_reverse_iterator否

最佳實踐

  1. 只讀遍歷用 cbegin()/cend()(配合 for (const auto& e : vec))。
  2. 需修改容器結構(如 partition、sort、erase)必須用 begin()/end()。
  3. 自定義算法模板時,用 std::iterator_traits 檢查迭代器類別。
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved