微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

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

如何解决排序行为前后的列表和迭代器

我正在使用cpp中的STL并找到列表。

写下面的代码

#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

来自cppreferencestd::list::sort

std :: sort需要随机访问迭代器,因此不能与 清单。此函数也不同于std :: sort,因为它没有 要求列表的元素类型是可交换的,保留 所有迭代器的值,并执行稳定的排序。

使用std::sort,迭代器将失效。 std::list::sort并非如此。粗心地说,迭代到std::list中的迭代器通常比其他迭代器更稳定。在您的示例中,it10it11仍指向相同的元素。排序后,位于第一位置的元素不再位于第一位置。它位于第二个但最后一个位置,并且it11仍指向列表end

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

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。