迭代器究竟是如何工作的?(多项选择题)
How exactly do iterators work? (multiple-choice)
我很困惑,为什么这个选择题的最终答案(选项e)是假的:
Which of the following statements is the most accurate regarding linked lists?
a. Linked-lists take up more space than STL vectors because they allocate extra storage
space for future growth.
b. The asymptotic complexity of inserting at the end of a doubly-linked list container
storing only the pointer to the first element is O(1).
c. A loop in a singly-linked-list can be found in O(log(n)) time and O(n) memory overhead
d. A loop in a singly-linked-list can be found in O(n) time and O(1) memory overhead.
e. The number of elements in a linked-list is end_ptr -start_ptr + 1, where start_ptr points
to the first element in the linked list and end_ptr points to the last item of the linked-list.
也就是说,为什么 d和e不是都正确?在什么情况下迭代器会返回带有end_ptr-start_ptr+1
的大小,在什么情况下不会返回?这个选项应该写end_ptr-start_ptr
吗?
链表不能保证是连续的(事实上,从来都不是——至少在实际场景中不是)。
这意味着减去它们的迭代器不能是一个常数时间操作(好吧,它可以是,但不是没有不必要的权衡)。
通常,除非是常量时间操作,否则在迭代器上不定义加减操作符。
同样,即使可以相减它们,迭代器也指向最后一个元素后一处,而不是最后一个元素。这意味着length = end - begin
。没有必要带一个人。
例如,使用std::vector
:
size_t len = v.end() - v.begin();
(虽然你通常只使用v.size()
)
与vector不同,list中的元素不是存储在连续的位置。因此,链表list.end()应该为空,以标记列表的结束。这就是为什么你不能通过算术得到列表的大小。而且,结束指向一个无效的项,即在最后一个有效元素之后的一个项。
相关文章:
- 传递给std::function template的template参数究竟代表什么
- C++关于指针和使用函数将它们启动到堆的行为究竟是什么?
- 究竟如何工作范围?
- 当使用对象名称后带有 [] 的类对象时,您究竟会传入什么.C++
- 哪种方式更快?究竟发生了什么,我们没有看到什么?
- 当我使用 void 函数的返回值(通过强制转换函数指针)时,究竟会发生什么?
- 串行端口写入究竟如何从缓冲区实际写入数据?
- DrawShadow 中的 Elevation 究竟有什么作用?
- 究竟是什么设置了_WIN32或_WIN64预处理器?
- 我的重复检查代码中的错误究竟在哪里?
- GCC 的 -Wpsabi 选项究竟有什么作用?压制它意味着什么?
- 这个编译器错误究竟希望我执行什么?
- 查找表究竟是如何工作的,以及如何实现它们
- 在陈述"Implementation-defined"时,什么样的软件是"Implementation"的一部分?究竟什么是"Implementation"?
- 变量或标识符存储在C++中究竟在哪里?
- 究竟什么是"位填充"或"填充位"?
- 究竟发生了什么,我们需要在 c++ 中双重调度/访客
- 内存分配究竟是如何发生的,Java和C如何交互以跟踪同一对象?
- std::async 究竟是如何执行的?
- 迭代器究竟是如何工作的?(多项选择题)