为什么 `std::set<T>::end()` 不等于 `std::set<T>::iterator{}`? [英] Why does not `std::set<T>::end()` compare equal to `std::set<T>::iterator{}`?
问题描述
编译这段代码:
#include <set>
#include <iostream>
int main(int argc, char * argv[]){
std::set<int> test;
std::cout << (test.end() == std::set<int>::iterator{}) << std::endl;
std::cout << (test.begin() == std::set<int>::iterator{}) << std::endl;
std::cout << (test.begin() == test.end()) << std::endl;
return 0;
}
它输出(在 gcc 11.1 和 clang 12.0.0 上测试):
It outputs (tested on gcc 11.1 and clang 12.0.0):
0
0
1
...但是,如果我参考 https://timsong-cpp.github.io/cppwp/n4659/iterators#forward.iterators-2
...However, if I refer to https://timsong-cpp.github.io/cppwp/n4659/iterators#forward.iterators-2
前向迭代器的 == 域是相同底层序列上的迭代器的域.但是,值初始化的迭代器可以进行比较,并且应该与相同类型的其他值初始化的迭代器进行比较.[ 注意:值初始化的迭代器的行为就像它们在同一空序列的末尾之后引用一样.— 尾注 ]
The domain of == for forward iterators is that of iterators over the same underlying sequence. However, value-initialized iterators may be compared and shall compare equal to other value-initialized iterators of the same type. [ Note: Value-initialized iterators behave as if they refer past the end of the same empty sequence. — end note ]
...那么 std::set<int>::iterator{}
就是我理解的值初始化";(请注意,我使用临时变量得到了相同的结果),我希望输出为:
...Then std::set<int>::iterator{}
is what I understand to be "value-initialized" (note that I get the same result using a temporary variable), and I would expect the output to be :
1
1
1
我错过了什么?
推荐答案
前向迭代器的 == 域是相同底层序列上的迭代器的域.
The domain of == for forward iterators is that of iterators over the same underlying sequence.
所以...可以用 ==
比较来自同一序列的迭代器.
So... one can compare iterators from the same sequence with ==
.
但是,值初始化的迭代器可以进行比较,并且应该与相同类型的其他值初始化的迭代器进行比较.
However, value-initialized iterators may be compared and shall compare equal to other value-initialized iterators of the same type.
所以...可以用 ==
比较两个相同类型的值初始化迭代器.
So... one can compare two value-initialized iterators of the same type with ==
.
注意:值初始化的迭代器的行为就像它们在同一空序列的末尾之后引用一样.
Note: Value-initialized iterators behave as if they refer past the end of the same empty sequence.
注释不是规范性的,但它描述的是对您隐藏了一些空序列,并且值初始化的迭代器表现得好像它们指的是过去这个序列的结束迭代器.
Notes are not normative, but this is describing that there is some empty sequence hidden from you, and the value-initialized iterators act as if they refer to the past the end iterator of this sequence.
这就是说,就好像标准库为自己实例化了一个 std::set
和一个引用 .end()
的值初始化迭代器代码>那个.
This is saying that it is as if the standard library instantiated for itself a std::set<int>
and a value-initialized iterator referred to the .end()
of that.
注释与上述一致.如果值初始化的迭代器表现得好像它们都指向同一个序列,那么在同一点,它们将是可比较的并且比较相等.
The note is consistent with the above. If value-initialized iterators act as if they all point into the same sequence, at the same point, they will be comparable and compare equal.
这篇关于为什么 `std::set<T>::end()` 不等于 `std::set<T>::iterator{}`?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!