迭代器究竟是如何工作的?(多项选择题)

How exactly do iterators work? (multiple-choice)

本文关键字:选择题 究竟 何工作 迭代器 工作      更新时间:2023-10-16

我很困惑,为什么这个选择题的最终答案(选项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()应该为空,以标记列表的结束。这就是为什么你不能通过算术得到列表的大小。而且,结束指向一个无效的项,即在最后一个有效元素之后的一个项。