2012-10-23 33 views
1

我不明白我测试过的这个非常简单的列表的问题在哪里。这个想法是让我的位置在列表中的项目。 我通常知道我不会用列表来做到这一点。 然而,这个工作当我设置item = 11item = 12item = 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; 
} 

回答

7

moveToItem()被称为所以返回的迭代器是指已被破坏一个list的项目正在取得列表L的副本。通过引用传递list代替:

list<int>::iterator moveToItem(int item, list<int>& L, int& pos) 
               //^ 

你也应该防止去过去的while条件listend(),解引用it之前。

如果这不是一个练习考虑使用STL算法std::find()std::distance()代替:

#include <iterator> 
#include <algorithm> 

std::list<int>::iterator it = std::find(L.begin(), L.end(), 41); 
if (it != L.end()) 
{ 
    std::cout << "at position " 
       << std::distance(L.begin(), it) 
       << " there's the item " 
       << *it 
       << "\n"; 
} 
+0

谢谢,就是这样! :) – FerranMG

0

打电话给你发名单的list<int>::iterator moveToItem(int item, list<int> L, int& pos)当前副本的时候你应该通过引用到列表中。

所以你的方法应该是list<int>::iterator moveToItem(int item, list<int>& L, int& pos)。你可以保持你的方法的正文一样。

0

您正在按值查看列表。因此,返回的迭代器是该函数的本地参数L的迭代器,因此一旦函数返回(并且L被破坏)就无效。你应该采取L参考:

list<int>::iterator moveToItem(int item, list<int> &L, int& pos) 

性能方面它是不是最好的主意,采取这样的可能大数据结构由值列表,反正。

相关问题