简体   繁体   中英

c++ iterator loop vs index loop

I know this is very stupid question, but I wanted to clarify this.

Let's say I have one string vector looks like,

vector<int> vnTemp; // suppose this vector has {1,2,3,4,5}
vector<int>::iterator vn_it;

//Now, I want to print out only 1 to 4.
for(int i=0; i<4; ++i)
    cout << vnTemp[i] << endl;

Quite simple. but what should I do when I want to print out the equivalent result by using iterator? for exmample,

// .. continuing from the code above
for(vn_it = vnTemp.begin(); vn_it != vnTemp.end()-1; ++vn_it)
    cout << *it << endl;

Of course, vnTemp.end()-1 will lead an error since it's pointer.

what is the equivalent for loop in this case? and is there any performance difference when they both are compiled in optimized(-o) mode?


Edit:

I've just realized this actually works with vector . The problem happened when I was using boost::tokenizer the code is like this:

typedef boost::tokenizer<boost::char_separator<char> > tokenizer;

boost::char_separator<char> sep("_");
tokenizer::iterator tok_it;

tokenizer tokens(strLine, sep); //strLine is some string line
for(tok_it=tokens.begin(); tok_it != tokens.end(); ++tok_it){
... }

This was the original code, and error occurs when I try to say tokens.end()-1 in a for loop.

Is there any way that I can fix this problem? Sorry about the ambiguity.

boost::tokenizer only provides a forward iterator; which means that you can't subtract from an tokenizer iterator. If you want your loop to avoid processing the last token you are going to have to "look-ahead" before you process the token you are on. Something like this

tokenizer tokens(strLine, sep); //strLine is some string line
tok_it = tokens.begin();
if(tok_it!=tokens.end())
{
    ++tok_it;
    for(auto last_tok = tokens.begin(); tok_it != tokens.end(); ++tok_it){
        // Process last_tok here
        . . .
       last_tok = tok_it;    
    }
}

Edit: An alternative approach would be to copy the tokens into a container with more flexible iterators:

std::vector<std::string> resultingTokens(tokens.begin(), tokens.end());
for(auto tok=resultingTokens.begin(); tok!=resultingTokens.end()-1; ++tok)
{
    // whatever
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM