x404.co.uk
http://www.x404.co.uk/forum/

C++ for loop
http://www.x404.co.uk/forum/viewtopic.php?f=4&t=12173
Page 1 of 1

Author:  Fogmeister [ Thu Jan 20, 2011 12:39 pm ]
Post subject:  C++ for loop

Just going through my C++ book and came across an exercise about iterators and vectors and stuff.

It asked me to write a program (using iterators in a for loop) that would take ints into a vector and then reverse the vector before printing it.

i.e. if I enter 1 2 3 4 5 into the console window it would print out as 5 4 3 2 1 (with new lines instead of spaces).

The for loop I wrote went like this...

data is my vector storing the inputs.

Code:
for(vector<int>::iterator up(data.begin()), down(data.end() - 1) ; up < down ; ++up, --down)
{
    //swap entries
}

i.e. up starts at the front and goes up. down starts at the last entry (NB not the off the end entry) and goes down. if up >= down then it ends.

This worked perfectly and fit everything into the for loop control. It seemed to work a treat.

However, the book came up with this...

Code:
for (vector<int>::iterator start(data.begin()), end(data.end()) ; start != end ; /*nothing here*/)
{
    --end;
    if (start != end)
    {
        //swap entries
        ++start;
    }
}

It seems like their way is a lot more long winded and harder to read (for me anyway).

Which would you prefer?

Author:  forquare1 [ Thu Jan 20, 2011 3:39 pm ]
Post subject:  Re: C++ for loop

Neither of them look particularly fun...Could you not use some sort of a foreach loop?

Author:  Fogmeister [ Thu Jan 20, 2011 4:27 pm ]
Post subject:  Re: C++ for loop

forquare1 wrote:
Neither of them look particularly fun...Could you not use some sort of a foreach loop?

I've not got to that part yet :D

The loop I wrote isn't that messy is it?

It just has 2 variables that control the loop as opposed to 1.

Author:  Fogmeister [ Thu Jan 20, 2011 5:01 pm ]
Post subject:  Re: C++ for loop

forquare1 wrote:
Neither of them look particularly fun...Could you not use some sort of a foreach loop?

You could also use the data.reverse() function but it as it was about learning the format of loop s and iterators they said not to :D

Author:  finlay666 [ Thu Jan 20, 2011 6:23 pm ]
Post subject:  Re: C++ for loop

The book has just done a while loop with the start values initialised in the start, for loops put the iterations at the start

IMO they have overcomplicated it

Page 1 of 1 All times are UTC
Powered by phpBB® Forum Software © phpBB Group
https://www.phpbb.com/