在使用 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++,減少臨時對象開銷。