将默认构造的迭代器与运算符==进行比较
C++ 标准是否规定我应该能够比较两个默认构造的 STL 迭代器是否相等? 默认构造的迭代器是否可相等比较?
我想要以下内容,例如使用 std::list:
void foo(const std::list<int>::iterator iter) {
if (iter == std::list<int>::iterator()) {
// Something
}
}
std::list<int>::iterator i;
foo(i);
我在这里想要的是类似迭代器的 NULL 值,但我不确定它是否合法。 在 Visual Studio 2008 附带的 STL 实现中,它们在 std::list 的运算符 ==() 中包含断言,以排除这种用法。 (他们检查每个迭代器是否由同一个容器“拥有”,并且默认构造的迭代器没有容器。)这将暗示它不合法,或者可能他们过于热心。
Does the C++ Standard say I should be able to compare two default-constructed STL iterators for equality? Are default-constructed iterators equality-comparable?
I want the following, using std::list for example:
void foo(const std::list<int>::iterator iter) {
if (iter == std::list<int>::iterator()) {
// Something
}
}
std::list<int>::iterator i;
foo(i);
What I want here is something like a NULL value for iterators, but I'm not sure if it's legal. In the STL implementation included with Visual Studio 2008, they include assertions in std::list's operator==() that preclude this usage. (They check that each iterator is "owned" by the same container and default-constructed iterators have no container.) This would hint that it's not legal, or perhaps that they're being over-zealous.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
规范说默认构造函数的后置条件是迭代器是单数。 相等的比较未定义,因此在某些实现中可能会有所不同。
Specification says that the postcondition of default constructor is that iterator is singular. The comparison for equality are undefined, so it may be different in some implementation.
我相信您应该将范围传递给该函数。
I believe you should pass a range to the function.
这将在 C++14 中改变。 [forward.iterators] N3936 的 24.2.5p2 说
This is going to change in C++14. [forward.iterators] 24.2.5p2 of N3936 says
好吧,我来一刺。 C++ 标准,第 24.1/5 节:
所以,不,它们不能进行比较。
OK, I'll take a stab. The C++ Standard, Section 24.1/5:
So, no, they can't be compared.