[] std::list的操作符

[] operator for std::list?

本文关键字:操作符 list std      更新时间:2023-10-16

我在一种情况下,我不能使用vector,因为我使用&element[x],然后添加更多的项目,所以指针无效。问题是std::list似乎没有超载operator [],也没有提供at()方法。因此,我认为可以模拟at()的唯一方法是使用迭代器。然而,有更好的方法来做到这一点吗?

你应该重新考虑你的设计。

尝试用std::list模拟operator[]at将导致性能灾难:这些操作将花费O(N)而不是O(1)时间,因为std::list::iterator是双向迭代器,而不是随机访问迭代器。因此,如果现在遍历容器并对每个元素调用[]at,结果将是O(N*N)而不是O(N)。

这就是为什么std::list没有提供这些操作

#include <iterator>
std::list<int> l;
std::list<int>::iterator it = l.begin();
std::advance(it, 37);

对于非随机访问迭代器(如list),这当然需要线性时间。

不std::list是链表。直接访问一个元素是不可能的。唯一的可能是从开始遍历元素