这个简单的std :: list中的bug在哪里?

Fer*_*nMG 1 c++ stl list

我无法理解我一直在测试这个非常简单的列表的问题.想法是将项目放在列表中的位置i.我知道我通常不会使用列表来做到这一点.但是,这在我设置时有效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.

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;
}
Run Code Online (Sandbox Code Playgroud)

hmj*_*mjd 7

调用LmoveToItem()会生成列表的副本,因此返回的迭代器指的list是已被破坏的项目.list通过引用传递:

list<int>::iterator moveToItem(int item, list<int>& L, int& pos)
                                                //^
Run Code Online (Sandbox Code Playgroud)

你也应该防止去过去end()listwhile情况下,提领前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";
}
Run Code Online (Sandbox Code Playgroud)