Re: Iterator questions...
"Jim Langston" <tazmaster@rocketmail.com> wrote in message
news:NA7Xj.172$J43.23@newsfe05.lga...
barcaroller wrote:
I've noticed that neither container.begin() nor container.end() return
an error when the container is empty, so I get a nasty segfault when I
dereference the iterator. Do I have to check if the container is
empty every time I use an iterator, or am I missing something?
You are missing something. For an empty containter .begin() == .end()
Aren't you checking to make sure your iteratores aren't equal to .end()?
One of the most common uses of .begin() and .end() is in a for loop, such
as:
std::list<int> Data;
for ( std::list<int>::iterator it = Data.begin(); it != Data.end(); ++it )
{
// it is guaranteed to be pointing to an item in the list
}
Actually, I'm not using the iterator in a loop. Briefly, I save the
iterator of the last successful find(). Before I call find() again, I first
check if the last iterator points to the info that I need. If not, then I
call find(). In essence, I'm caching the iterator to improve performance,
by avoiding a call to find().
Note: where find() is either a member function or an algorithm.
However, caching iterators has its own problems. Initialization,
invalidation, etc.