artemonster
artemonster

Reputation: 763

Elegant check for std::find "not found" condition

I am using most common way to search for some particular object in a small list:

iterator=std::find(begin, end, whatToFind);

If std::find does not find the element, it will return iterator at the end of the container, so the most common and suggested on SO way is:

if (iterator != end) {
    found 
} else {
    not found
}

But what if the element I am looking for IS at the end? Or maybe it is a list, containing ONLY the element I am looking for? Do I really need to manually check for these conditions or there is some sort of flag (which I don't know), which definitely marks the not_found case? Thank you.

Upvotes: 1

Views: 2418

Answers (3)

masoud
masoud

Reputation: 56479

If the searching item is at the end of the list (container) then the iterator is not referring to the end(). The iterator end() is a reserved (placeholder) iterator, the next one after your last item. However it doesn't apply for begin() which is really refers to the first item inside the container. Generally in C++ ranges are in this form [begin, end).

enter image description here

Returns an iterator to the element following the last element of the container. This element acts as a placeholder; attempting to access it results in undefined behavior.

Upvotes: 4

NPE
NPE

Reputation: 500397

end() does not point to a valid element (it points to one past the last element). Therefore there is no ambiguity.

Upvotes: 3

Benjamin Lindley
Benjamin Lindley

Reputation: 103713

But what if the element I am looking for IS at the end?

It cannot be. The end, (i.e. the iterator returned by end()) does not point to a valid element. The last element (if there are more than zero elements) in the container is the one pointed at by the iterator preceding end().

Or maybe it is a list, containing ONLY the element I am looking for?

Then find will not return end. It will return begin. Which, in that case, directly precedes end.

Upvotes: 3

Related Questions