views:

263

answers:

3

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  A: 

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++;
    }
}
AraK
Possibly true, but doesn't answer the question.
anon
Yup, just my 2 cents :)
AraK
I understand what you're saying, but the semantics really call for a single item -- much like std::list::erase(). I may be abusing the concept of an iterator; that's what I'm interested in discovering.
Adrian
I got your point :)
AraK
AraK, by what means can you have have a "null" iterator to pass in?
Andy J Buchanan
@Andy, I didn't understand your question.
AraK
+6  A: 

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.

anon
Nice, you got it :)
AraK
+1  A: 

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.

lionbest