[] std::list的操作符
[] operator for std::list?
我在一种情况下,我不能使用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是链表。直接访问一个元素是不可能的。唯一的可能是从开始遍历元素
相关文章:
- 使用std::multimap迭代器创建std::list
- 来自 std::list 的迭代器 .end() 按预期返回"0xcdcdcdcdcdcdcdcd"但 .begin()
- 如何在 C 中正确使用 libiconv 使其不会报告"Arg list too long"?
- C++中带有List类的迭代器Segfault
- 使用"std::unordereded_map"映射到"std::list"对象
- GCC对可能有效的代码抛出init list生存期警告
- 使用std::list创建循环链表
- 重载Singly Linked List中的赋值运算符
- '[](std::list& list)<int>{return std::move(list)}(list)' 是否保证将 'list' 留空?
- 如果 KEY 是 std::list 或 std::vector 而不是值,那么 std::map 的默认行为是什么?
- 为什么这个 std::queue/指向结构的指针列表直到 List.Size() == 0 才释放内存?
- "std::list::splice(std::const_iterator pos, std::list&& other)"是否保证将"其他"留空?
- 从嵌套循环中的 std::list 中删除将返回访问冲突
- QStringList vs list<shared_ptr<QString>> 性能比较C++
- 包含 std::list 的结构体的 C++ 初始化
- 在C++中使用 Catch 测试框架编译错误"error: expected ';' at end of declaration list"
- C++ assigment std::list:<typename>:itrator 在 main 中工作,但在方法中它不起作用
- 在基于范围的 for 循环期间插入 std::list 的后面
- 循环挂起迭代的 std::擦除 on std::list
- [] std::list的操作符