Re: iterator on for loop with multiple ending conditions
{ Top-posting and including the clc++m banner is discouraged. -mod/sk }
If you want both of the terminating conditions in your for loop to
terminate you out of the loop i.e
testIndex<3 , vi!=testyVec.end()
then you need to change the above code to the following:
testIndex<3 && vi!=testyVec.end()
and your program will look like this.
The syntax with the comma is a correct syntax but it does not behave
like you want it to.
#include <iostream>
#include <vector>
using namespace std;
void main()
{
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++;
}
}
janeywit wrote:
Hi,
I'm no expert in C++ and I've quite a while tracking down a problem
which I believe I am summarising here. If anybody can help me out I'd
be very grateful!
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?)
Thank you!
Jane
{ banner stripped }
--
[ See http://www.gotw.ca/resources/clcm.htm for info about ]
[ comp.lang.c++.moderated. First time posters: Do this! ]