Re: iterator on for loop with multiple ending conditions
janeywit schrieb:
The following piece of code doesn't work as I expect:
int testIndex=0;
vector<int> testyVec;
testyVec.push_back(1);
testyVec.push_back(2);
testyVec.push_back(3);
testyVec.push_back(4);
testyVec.push_back(5);
typedef vector<int>::iterator vecIterator;
vecIterator vi;
for(vi=testyVec.begin(); testIndex<3, vi!=testyVec.end();
++vi)
{
cout<<"itr: testIndex is "<<testIndex<< " and testyVec item
is "<<(*vi)<<"\n";
testIndex++;
}
I expect the for loop to end after 3 iterations due to one of the
ending conditions "testIndex<3". It doesn't. It goes on until the
second ending condition is reached. In fact if I switch the order of
the ending conditions then it always ignores the first one. Am I
using incorrect syntax... is there some bug ... or what am I missing?!
(I know I can do this by putting && between the two conditions but I
thought the other syntax was also correct?)
You have actually recognized your problem on your own. The reason is
that you should use the proposed expression
testIndex<3 && vi!=testyVec.end()
as test condition. Your for-loop currently uses a comma expression
a, b
The effect of the comma expression is precisely described by 5.18 as
"[..] A pair of expressions separated by a comma is evaluated
left-to-right and the value of the left expression is discarded.[..]
The type and value of the result are the type and value of the right
operand;[..]"
The comma operator is useful in situations, when it is neccessary
or reasonable to perform more than one evaluation in one
expressions, especially if order of evaluation is importand.
Therefore in your for-loop the first expression a = testIndex<3
is evaluated and returns either true or false. The result is ignored
and the second expression is evaluated, which's result is returned.
This has essentially the same end-condition as if you would only
have used the test vi!=testyVec.end().
Greetings from Bremen,
Daniel Kr?gler
--
[ See http://www.gotw.ca/resources/clcm.htm for info about ]
[ comp.lang.c++.moderated. First time posters: Do this! ]