Why isn#39;t there an operator[] for a std::list?(为什么 std::list 没有运算符 []?)
问题描述
谁能解释为什么没有为 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)内完成,这对于vector
和 deque
,但不是 list
.
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
算法:
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 没有运算符 []?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:为什么 std::list 没有运算符 []?


基础教程推荐
- 在 C++ 中计算滚动/移动平均值 2021-01-01
- 如何将 std::pair 的排序 std::list 转换为 std::map 2022-01-01
- 如何通过C程序打开命令提示符Cmd 2022-12-09
- 静态库、静态链接动态库和动态链接动态库的 .lib 文件里面是什么? 2021-01-01
- 如何检查GTK+3.0中的小部件类型? 2022-11-30
- 这个宏可以转换成函数吗? 2022-01-01
- 常量变量在标题中不起作用 2021-01-01
- 我有静态或动态 boost 库吗? 2021-01-01
- C++结构和函数声明。为什么它不能编译? 2022-11-07
- 如何在 C++ 中初始化静态常量成员? 2022-01-01