Re: Help... global iterator causes assertion failure
On Fri, 14 Sep 2007 13:36:00 -0700, Lee <Lee> wrote:
I'm a newbie, and don't know why the else-if statement fails. Besides, I
don't know how to check if the global iterator "m_iter" has been initialized
or not. Can someone answer them? Thanks In Advance...
typedef std::list<int> list_int;
list_int::iterator m_iter;
void foo( list_int myList )
{
list_int::iterator itEnd = myList.end();
list_int::iterator it = myList.begin();
// The next IF is the only way that I know to find a list-iterator has
not been initialized.
if( m_iter._Mynode() == NULL ) // what is the better way?
There is no way. Iterators do not have "null" values, and container
iterators only make sense relative to other iterators obtained from the
container from which they were initialized.
m_iter = it;
else if( m_iter == itEnd ) // assertion error!
m_iter = it;
else
m_iter++;
}
main() {
list_int myList;
for ( long ii = 0; ii < 10; ii++ ) myList.push_back(ii);
Why use long here? It's rare to use long as a loop control variable type,
and you have a list of ints anyway.
foo( myList );
foo( myList );
}
This code doesn't make a lot of sense. You should not have a global
iterator, and for the sake of argument, the iterator should be a foo
parameter:
void foo(list_int& lst, list_int::iterator& iter)
{
...
}
I've made the list argument a reference, so it can be used to assign to
iter, but that's not going to help your original approach. You must assume
either that iter is valid, in which case, you can do things with it, or
it's not valid, in which case, you must assign it a valid value before
using it. If this initialization-before-use doesn't fall out naturally,
then you will have to track the initialization status in some way.
--
Doug Harrison
Visual C++ MVP