c++ - 排序行为前后的列表和迭代器
问题描述
我正在通过 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 需要随机访问迭代器,因此不能与 list 一起使用。此函数与 std::sort 的不同还在于它不需要列表的元素类型是可交换的,保留所有迭代器的值,并执行稳定的排序。
随着std::sort
迭代器失效。情况并非如此std::list::sort
。粗略地说,std::list
s 中的迭代器通常比其他迭代器更稳定。在您的示例中it10
,it11
仍然指向相同的元素。排序后,位于第一个位置的元素不再位于第一个位置。它位于倒数第二个位置,it11
仍然指向列表end
。
考虑到 astd::list
是一个链表,要更改顺序,不需要修改或移动元素到内存中的其他位置,只需更新链接。
推荐阅读
- r - 是否可以像 powerbi 一样在 R 中的图表中添加过滤器?
- css - CSS object-fit:cover 不适用于 EXIF 方向的 JPEG img 更多 1
- hibernate-envers - 自定义审计日志与 Hibernate Envers
- functional-programming - 为什么这会导致无限循环 [SICP]?
- javascript - 使颜色选择器可拖动而不是仅单击
- node.js - 在 NodeJS 和 MongoDB 中使用 cronjobs 的项目任务计划
- android - 为什么我没有将 firebase 的输出作为字符串获取?
- opencv - 如何将函数捕获的帧从另一个库传递给 OpenCV 函数?
- python - 如何在 python """ 引号字符串中添加转义?
- sql - 达到触发函数postgreSQL中的参数