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 thisEdit: An alternative approach would be to copy the tokens into a container with more flexible iterators: