列表和迭代器排序前后的行为

List and Iterator after and before sorting behavior

我在 cpp 中通过 STL,我找到了 List。

写下代码:

#include <bits/stdc++.h>
using namespace std;

int main()
{
    list<int> ls;
    ls.push_back(23);
    ls.push_front(34);
    ls.push_front(39);
    ls.push_front(334);
    ls.push_front(434);
    ls.push_front(7834);
    ls.push_front(634);
    ls.push_front(934);

    list<int>::iterator it10 = ls.begin();
    list<int>::iterator it11 = ls.end();
    list<int>::reverse_iterator it12 = ls.rbegin();
    list<int>::reverse_iterator it13 = ls.rend();

    ls.sort();

    for (auto it = it10; it != it11; it++)
    {
        cout << *(it) << "\n";
    }
}

所以在这里我在对列表进行排序之前定义了迭代器,我得到的输出为:

934
7834

但是如果我在定义迭代器之前对它们进行排序,例如:


ls.sort();

list<int>::iterator it10 = ls.begin();
list<int>::iterator it11 = ls.end();
list<int>::reverse_iterator it12 = ls.rbegin();
list<int>::reverse_iterator it13 = ls.rend();

我得到正确的输出:

23
34
39
334
434
634
934
7834

为什么会这样?这是如何工作的?请解释。 谢谢!

it10 是列表中元素 934 的迭代器。 it11 是指向列表末尾的迭代器。排序后 it10 是指向元素 934 的迭代器,而 it11 是指向列表末尾的迭代器。排序后从934开始的元素为:

943 
7834

来自 cppreference 关于 std::list::sort:

std::sort requires random access iterators and so cannot be used with list . This function also differs from std::sort in that it does not require the element type of the list to be swappable, preserves the values of all iterators, and performs a stable sort.

使用 std::sort 迭代器会失效。 std::list::sort 不是这种情况。草率地说,std::lists 的迭代器通常比其他迭代器更稳定。在您的示例中,it10it11 仍然指向相同的元素。排序后,原来排在第一位的元素不再排在第一位。它在第二个也是最后一个位置并且 it11 仍然指向列表 end.

考虑到 std::list 是一个链表,要更改顺序,无需修改或将元素移动到内存中的其他位置,只需更新链接即可。