Using an STL Iterator without initialising it

℡╲_俬逩灬. 提交于 2019-12-24 03:45:13

问题


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.


回答1:


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




回答2:


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.




回答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 )
{
    ...
}



回答4:


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



来源:https://stackoverflow.com/questions/469849/using-an-stl-iterator-without-initialising-it

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!