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

C++ vector 迭代器轉換錯誤與查找邏輯修正

     編輯:程式設計疑難解答

問題背景

在使用 std::vector<Information*> 存儲指針時,嘗試將 begin() 返回的迭代器直接賦值給 Information* 指針,導致編譯錯誤:無法從“std::_Vector_iterator<_Myvec>”轉換為“Information *”。同時,查找循環的邏輯也存在缺陷。

錯誤代碼示例

Information *temp;
temp = card.begin(); // 錯誤:迭代器不能直接賦值給指針
while(i <= card.size()) {
    if((temp->Get_Name()) == tempname) { return temp; }
    temp++; // 迭代器遞增方式不當
    i++;
}

正確寫法

應使用迭代器遍歷容器,通過解引用 *it 獲取元素指針:

Information *temp = NULL;
std::vector<Information*>::iterator it = card.begin();
while(it != card.end()) { // 建議用 != 而非 <
    temp = *it; // 解引用獲取 Information*
    if((temp->Get_Name()) == tempname) {
        return temp;
    }
    ++it; // 前置遞增效率更高
}
return NULL;

關鍵點總結

  • vector::begin() 返回的是迭代器,非指針,需通過 *it 取值。
  • 循環條件推薦 it != card.end(),避免越界風險。
  • 使用前置遞增 ++it 而非後置 it++,減少臨時對象開銷。
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved