2

I would like to do something like this:

container::iterator it = NULL;

switch ( eSomeEnum )
{
case Container1:
it = vecContainer1.begin();
break;

case Container2:
it = vecContainer2.begin();
break;
...


}

for( ; it != itEnd ; ++it )
{ 
..
}

But I can't create and initialise an iterator to NULL. Is there some way I can do this? Ideally I would just create and assign the iterator in the switch, but then it would go out of scope immediately.

Konrad
  • 37,861
  • 31
  • 75
  • 112

4 Answers4

11

You just needn't initialize it at all, because iterators are DefaultConstructible.

jpalecek
  • 45,889
  • 7
  • 97
  • 139
6

All you should need to do is change

container::iterator it = NULL;

to

container::iterator it;

and I think your code will work as intended.

Evan Shaw
  • 22,406
  • 5
  • 67
  • 60
  • The OP stated that he can't do it, g++ and clang++ do not accept a null comparison or a null initialization. So AFAIK this is a meaningless answer, you shouldn't post things you "think" about as when it turns out wrong it harms the community in general. – Hassan Syed Mar 11 '11 at 07:33
  • 2
    This answer is essentially the same as the one that was accepted. How is it wrong? I'm happy to correct mistakes. – Evan Shaw Mar 30 '11 at 09:19
3

You actually need a range, not just begin iterator. Note, you can't compare iterators from different containers, so you better off selecting the range, not the iterator. You can use Boost.Range to achieve it:

#include <boost/range.hpp>
#include <boost/foreach.hpp>

boost::iterator_range< container::iterator > r;
switch( e )
{
    case Container1:
        r = boost::make_iterator_range( vecContainer1 );
    break;

    case Container2:
        r = boost::make_iterator_range( vecContainer2 );
    break;

    ...
}

BOOST_FOREACH( container::value_type value, r )
{
    ...
}
Vadim Ferderer
  • 901
  • 7
  • 11
1

As the loop tests for end, you should construct it to value what itEnd values.

Luc Hermitte
  • 30,988
  • 7
  • 63
  • 78