我不明白我測試過的這個非常簡單的列表的問題在哪裏。這個想法是讓我的位置在列表中的項目。 我通常知道我不會用列表來做到這一點。 然而,這個工作當我設置item = 11
,item = 12
和item = 13
(輸出將分別at position {1, 2, 3} there's the item {11, 12, 13}
),但是當我設置item = 10
,因爲輸出是at position 0 there's the item 6
這是行不通的。這個簡單的std :: list中的錯誤在哪裏?
int main(void)
{
list<int> L;
L.push_back(10);
L.push_back(11);
L.push_back(12);
L.push_back(13);
int item = 10;
int pos;
list<int>::iterator it = moveToItem(item, L, pos);
cout << "at position " << pos << " there's the item " << *it;
}
list<int>::iterator moveToItem(int item, list<int> L, int& pos)
{
pos = 0;
list<int>::iterator it = L.begin();
while(*it != item)
{
it++;
pos++;
}
return it;
}
謝謝,就是這樣! :) – FerranMG