当 first <= last 不满足时,C++ 标准对算法有何规定?
What does the C++ standard says for algorithms when first <= last is not fulfilled?
当条件 first <= last
未满足时,官方 C++ 标准对算法有何规定,first
和 last
是传递给标准算法之一的迭代器?
我看到三种可能性:
- 算法需要检查条件,如果条件不满足,算法什么都不做
- 算法需要抛出异常
- 这是未定义的行为,所以...任何事情都可能发生
我很困惑,因为在算法描述中我没有看到关于 first
和 last
.
的 requires
子句
EDIT1:这是对问题的简化。更准确的版本是“当无法通过连续应用 operator++
从 first
到达 last
时,算法会发生什么情况?
EDIT2:我问这个问题是因为我正在实施 std::reverse
的专业化,我想知道我是否应该检查这个条件,或者我是否可以允许函数在 [= 时做一些完全错误的事情12=] 无法从 first
?
访问
您要查找的文本在迭代器部分(强调我的):
[iterator.requirements.general]/7-8
An iterator j is called reachable from an iterator i if and only if there is a finite sequence of applications of
the expression ++i that makes i == j. If j is reachable from i, they refer to elements of the same sequence.
Most of the library’s algorithmic templates that operate on data structures have interfaces that use ranges.
A range is a pair of iterators that designate the beginning and end of the computation. A range [i,i) is an
empty range; in general, a range [i,j) refers to the elements in the data structure starting with the element
pointed to by i and up to but not including the element pointed to by j. Range [i,j) is valid if and only if
j is reachable from i. The result of the application of functions in the library to invalid ranges is undefined.
标准在这里明确指出,将无效(未满足)范围传递给标准算法会导致未定义的行为。算法本身确实以 [first, last)
格式指定范围。
请注意,/7 不允许交换随机访问迭代器的参数,因为您不能一遍又一遍地应用 ++first
来达到 last
。
当条件 first <= last
未满足时,官方 C++ 标准对算法有何规定,first
和 last
是传递给标准算法之一的迭代器?
我看到三种可能性:
- 算法需要检查条件,如果条件不满足,算法什么都不做
- 算法需要抛出异常
- 这是未定义的行为,所以...任何事情都可能发生
我很困惑,因为在算法描述中我没有看到关于 first
和 last
.
requires
子句
EDIT1:这是对问题的简化。更准确的版本是“当无法通过连续应用 operator++
从 first
到达 last
时,算法会发生什么情况?
EDIT2:我问这个问题是因为我正在实施 std::reverse
的专业化,我想知道我是否应该检查这个条件,或者我是否可以允许函数在 [= 时做一些完全错误的事情12=] 无法从 first
?
您要查找的文本在迭代器部分(强调我的):
[iterator.requirements.general]/7-8
An iterator j is called reachable from an iterator i if and only if there is a finite sequence of applications of the expression ++i that makes i == j. If j is reachable from i, they refer to elements of the same sequence.
Most of the library’s algorithmic templates that operate on data structures have interfaces that use ranges. A range is a pair of iterators that designate the beginning and end of the computation. A range [i,i) is an empty range; in general, a range [i,j) refers to the elements in the data structure starting with the element pointed to by i and up to but not including the element pointed to by j. Range [i,j) is valid if and only if j is reachable from i. The result of the application of functions in the library to invalid ranges is undefined.
标准在这里明确指出,将无效(未满足)范围传递给标准算法会导致未定义的行为。算法本身确实以 [first, last)
格式指定范围。
请注意,/7 不允许交换随机访问迭代器的参数,因为您不能一遍又一遍地应用 ++first
来达到 last
。