问题描述
任何人都可以解释为什么不是为std :: list实现的operator []?我搜索了一下,但没有找到答案。
Can anyone explain why isn't the operator[] implemented for a std::list? I've searched around a bit but haven't found an answer. It wouldn't be too hard to implement or am I missing something?
推荐答案
通过索引检索元素是一个O(n )操作的链接列表,这是 std :: list
是。因此,决定提供 operator []
将是欺骗性的,因为人们会被诱使主动使用它,然后你会看到如下代码:
Retrieving an element by index is an O(n) operation for linked list, which is what std::list
is. So it was decided that providing operator[]
would be deceptive, since people would be tempted to actively use it, and then you'd see code like:
std::list<int> xs;
for (int i = 0; i < xs.size(); ++i) {
int x = xs[i];
...
}
这是O(n ^ 2)非常讨厌。因此ISO C ++标准特别提到支持 operator []
的所有STL序列应该在摊销常量时间(23.1.1 [lib.sequence.reqmts] / 12)这是向量
和 deque
,但不是列表
。
which is O(n^2) - very nasty. So ISO C++ standard specifically mentions that all STL sequences that support operator[]
should do it in amortized constant time (23.1.1[lib.sequence.reqmts]/12), which is achievable for vector
and deque
, but not list
.
对于你真正需要这种东西的情况,你可以使用 std :: advance
算法: / p>
For cases where you actually need that sort of thing, you can use std::advance
algorithm:
int iter = xs.begin();
std::advance(iter, i);
int x = *iter;
这篇关于为什么std :: list没有运算符[]?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!