1

我不明白我一直在测试的这个非常简单的列表的问题在哪里。这个想法是在列表中的位置 i 处获取项目。我知道通常我不会使用列表来做到这一点。但是,当我设置item = 11,item = 12item = 13( 输出将分别为at position {1, 2, 3} there's the item {11, 12, 13}) 时有效,但是当我设置 时它不起作用,item = 10因为输出是at position 0 there's the item 6

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;
}
4

3 回答 3

7

L调用时正在制作列表的副本,moveToItem()因此返回的迭代器正在引用list已被破坏的 a 项。list而是通过引用传递:

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

在取消引用之前,您还应该防止越过条件end()list的。whileit

如果这不是练习,请考虑使用 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";
}
于 2012-10-23T09:05:49.527 回答
0

list<int>::iterator moveToItem(int item, list<int> L, int& pos)在调用当前制作的列表副本时,您应该传递对列表的引用。

所以你的方法应该是list<int>::iterator moveToItem(int item, list<int>& L, int& pos)。您可以保持方法的主体相同。

于 2012-10-23T09:07:20.817 回答
0

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

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

无论如何,在性能方面,将如此大的数据结构作为按值列表并不是最好的主意。

于 2012-10-23T09:14:00.267 回答