Page 1 of 1 |
|
Posted: Sat, 8th Apr 2017 01:44 Post subject: C++ Iterator |
|
 |
I have the following book code which is throwing up a "Expression: iterator not decrementable". It tries to read past vect.begin() after it completes going backwards, but why?
Code: |
#include <iostream>
#include <vector> // Include the vector header
using namespace std;
int main()
{
int count; // Loop counter
// Define a vector object.
vector<int> vect;
// Define an iterator object.
vector<int>::iterator iter;
// Use push_back to push values into the vector.
for (count = 0; count < 10; count++)
vect.push_back(count);
// Step the iterator through the vector, and use it to display the vector's contents.
cout << "Here are the values in vect: ";
for (iter = vect.begin(); iter < vect.end(); iter++)
{
cout << *iter << " ";
}
// Step the iterator through the vector backwards.
cout << "\nand here they are backwards: ";
for (iter = vect.end() - 1; iter >= vect.begin(); iter--)
{
cout << *iter << " ";
}
return 0;
}
|
|
|
Back to top |
|
 |
|
Posted: Sat, 8th Apr 2017 03:41 Post subject: |
|
 |
Made the following change:
Code: |
for (iter = vect.end() - 1; iter != vect.begin(); iter--)
|
Why >= not work but != work, what am I not understanding about vect.begin()? Thanks.
Sorry, never mind that will not get the first element.
|
|
Back to top |
|
 |
[mrt]
[Admin] Code Monkey
Posts: 1338
|
Posted: Tue, 18th Apr 2017 18:32 Post subject: |
|
 |
Hey,
Its quite simple. When you are at your last item, namely when iter = v.begin your postloop expression iter-- executes one last time pushing your iterator past its bounds.
Here is a little tip. To iterate backwards simply replace v.begin() with v.rbegin() and use your normal loop so basically it looks like this:
for(iter = v.rbegin(); iter != v.rend(); iter++)
Have fun!
teey
|
|
Back to top |
|
 |
|
Posted: Tue, 18th Apr 2017 18:47 Post subject: |
|
 |
Thanks mrt!
After I realized there was no way it was ever going to work I broke down and used a reverse_iterator and a FOR loop as you posted. I sent an e-mail to the author of the book and informed him of his codes oversight.
Thanks again!
|
|
Back to top |
|
 |
[mrt]
[Admin] Code Monkey
Posts: 1338
|
|
Back to top |
|
 |
|
|
Back to top |
|
 |
Page 1 of 1 |
All times are GMT + 1 Hour |