gpt4 book ai didi

c++ - 在迭代器的计算中,如果我使用 begin() 之前或 end() 之后的迭代器作为操作数,它的行为是否定义?

转载 作者:行者123 更新时间:2023-11-30 01:13:37 25 4
gpt4 key购买 nike

我做了一个实验:

#include <iostream>
#include <vector>

int main(void) {
std::vector<int> a{1, 2, 3};
std::vector<int>::iterator b = a.begin();
std::vector<int>::iterator c = a.end();
std::vector<int>::iterator d = b - 1;
std::vector<int>::iterator e = c + 1;
std::cout << true << std::endl;
std::cout << (d < b) << std::endl;
std::cout << (e > c) << std::endl;
return 0;
}

输出:

1
1
1

但是有人告诉我deque是未定义的行为,你怎么看?谢谢!

最佳答案

没有。

de 都是“单数迭代器”,因为它们既不指向序列中的元素,也不指向“尾后一个”伪-元素。

而且你几乎不能用单数迭代器做任何事情:

[C++11: 24.2.1/5]: Just as a regular pointer to an array guarantees that there is a pointer value pointing past the last element of the array, so for any iterator type there is an iterator value that points past the last element of a corresponding sequence. These values are called past-the-end values. Values of an iterator i for which the expression *i is defined are called dereferenceable. The library never assumes that past-the-end values are dereferenceable. Iterators can also have singular values that are not associated with any sequence. [ Example: After the declaration of an uninitialized pointer x (as with int* x;), x must always be assumed to have a singular value of a pointer. —end example ] Results of most expressions are undefined for singular values; the only exceptions are destroying an iterator that holds a singular value, the assignment of a non-singular value to an iterator that holds a singular value, and, for iterators that satisfy the DefaultConstructible requirements, using a value-initialized iterator as the source of a copy or move operation.

请注意,您不能对它们进行任意比较。

我很确定即使评估 a.begin() - 1a.end() + 1 也是 UB,但我找不到任何证据现在。

关于c++ - 在迭代器的计算中,如果我使用 begin() 之前或 end() 之后的迭代器作为操作数,它的行为是否定义?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31792101/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com