C++ STL - 为什么 std::forward_list 没有 size() 方法?

标签 c++ c++11 stl forward-list

我一直在使用 C++11 的 forward_list作为一个快速插入的容器,没有太多的内存开销,因为它是一个单链表。

在意识到 forward_list没有 size()方法,我对背后的推理有点困惑。难道它不能只维护一个私有(private)字段来跟踪插入和删除的节点,从而实现 O(1) size() 操作吗?

最佳答案

N2543是提案,里面有关于size()的详细讨论.

The choice between Option 3 [not providing size()] and Option 2 [providing a O(1) size()] is more a matter of judgment. I have chosen Option 3 for the same reason that I chose insert-after instead of insert-before: Option 3 is more consistent with the goal of zero overhead compared to a hand-written C-style linked list. Maintaining a count doubles the size of a forward_list object (one word for the list head and one for the count), and it slows down every operation that changes the number of nodes. In most cases this isn't a change in asymptotic complexity (the one change in asymptotic complexity is in one of the forms of splice), but it is nonzero overhead. It's a cost that all users would have to pay for, whether they need this feature or not, and, for users who care about maintaining a count, it's just as easy to maintain it outside the list, by incrementing the count with every insert and decrementing it with every erase, as it is to maintain the count within the list.

关于C++ STL - 为什么 std::forward_list 没有 size() 方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31822494/

相关文章:

c++ - 将原始数据包装在 std 容器中,如数组,具有运行时大小

C++11: "= {}"的类内初始化不适用于显式构造函数

c++ - multimap upper_bound 返回混淆

c++ - 处理无法实例化自身的对象的最佳方法?

c++ - 全局访问单例数据

c++ - 模拟流以进行测试

c++ - 我们可以在一条语句中拆分、操作和重新连接 C++ 中的字符串吗?

c++ - 如何初始化vector的模板子类

c++ - 如何使用 C++11 <atomic> 实现指向整数的指针的原子增量?

c++ - 访问对象列表中的非常量成员