我正在 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
是一个链表,为了改变顺序,不需要修改或移动元素到内存中的其他位置,只需要更新链接。
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句