Comparing default-constructed iterators with operator==

拟墨画扇 提交于 2020-01-21 03:00:26

问题


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.


回答1:


OK, I'll take a stab. The C++ Standard, Section 24.1/5:

Iterators can also have singular values that are not associated with any container. [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. ] Results of most expressions are undefined for singular values; the only excep- tion is an assignment of a non-singular value to an iterator that holds a singular value.

So, no, they can't be compared.




回答2:


This is going to change in C++14. [forward.iterators] 24.2.5p2 of N3936 says

However, value-initialized iterators may be compared and shall compare equal to other value-initialized iterators of the same type.




回答3:


I believe you should pass a range to the function.

void fun(std::list<int>::iterator beg, std::list<int>::iterator end)
{
    while(beg != end)
    {
        // do what you want here.
        beg++;
    }
}



回答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.



来源:https://stackoverflow.com/questions/1190112/comparing-default-constructed-iterators-with-operator

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!