C++双端队列迭代器有多聪明

How smart is C++ deque iterator

假设我有一个 std::deque<int> d 包含 100 个值,从 099。鉴于 the following

Unlike vectors, deques are not guaranteed to store all its elements in contiguous storage locations: accessing elements in a deque by offsetting a pointer to another element causes undefined behavior.

下面的行似乎无效:

int invalidResult = *(d.begin() + 81); // might give me 81, but NOT GUARANTEED, right?

我的问题是:迭代器会处理这个吗?

std::deque<int>::iterator it = d.begin();
int isThisValid = *(it + 81); // 81 every time? or does it result in undefined behavior?

有一次,我认为迭代器可以处理底层存储中的任何不连续性,但现在我不太确定了。显然,如果您使用 it++ 81 次,*it 将给您 81 作为结果。

有人可以肯定地说吗?

为了它的价值,我没有使用 C++11。

It appears line below is not valid:

int invalidResult = *(d.begin() + 81); // might give me 81, but NOT GUARANTEED, right?

恰恰相反。该语句完全有效并且行为得到保证(假设 d.size() >= 82)。这是因为 std::deque::begin returns 是迭代器,而不是指针,所以引用的规则不适用。

std::deque<int>::iterator it = d.begin();
int isThisValid = *(it + 81); // 81 every time? or does it result in undefined behavior?

这与前面的代码非常相似,只是您使用的是命名变量,而不是临时迭代器。行为完全相同。


以下是您不可以做的事情的示例:

int* pointer = &d.front();
pointer[offset] = 42; // oops

根据 this reference here a std::deque provides a RandomAccessIterator 根据您的示例肯定会起作用。

std::deque<int>::iterator it = d.begin();
int isThisValid = *(it + 81); // will be fine assuming the deque is that large