首页 > 解决方案 > 排序行为前后的列表和迭代器

问题描述

我正在通过 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

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

标签: c++liststl

解决方案


it10是列表中元素的迭代器934it11是列表末尾的迭代器。排序后it10是元素934it11迭代器,也是列表末尾的迭代器。934排序后开始的元素是:

943 
7834

cppreference关于std::list::sort

std::sort 需要随机访问迭代器,因此不能与 list 一起使用。此函数与 std::sort 的不同还在于它不需要列表的元素类型是可交换的,保留所有迭代器的值,并执行稳定的排序。

随着std::sort迭代器失效。情况并非如此std::list::sort。粗略地说,std::lists 中的迭代器通常比其他迭代器更稳定。在您的示例中it10it11仍然指向相同的元素。排序后,位于第一个位置的元素不再位于第一个位置。它位于倒数第二个位置,it11仍然指向列表end

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


推荐阅读