0

Hello

I'm trying to iterate backwards through a vector. with a while loop it works fine.
prints out:

12
8
4
1

However the for loop prints

196735
12
8
4

Could you please tell me why this is. Probably something wrong with my logic i don't know

I'm using the Dev C++ compiler.

Thanks in advance

#include<iostream>
#include<string>
#include <vector>
using namespace std;

int main(){

vector<int> myIntVector;


// Add some elements to myIntVector
myIntVector.push_back(1);
myIntVector.push_back(4);
myIntVector.push_back(8);
myIntVector.push_back(12);


vector<int>::iterator myIntVectorIterator;

cout << "For loop: "<<"\n"<<"\n"; 
for(myIntVectorIterator = myIntVector.end();myIntVectorIterator  != myIntVector.begin();myIntVectorIterator--)
{
      
	
	cout << (*myIntVectorIterator ) <<"\n";                    
}


cout <<"\n" <<"while loop: "<<"\n"<<"\n"; 
myIntVectorIterator = myIntVector.end();
while (myIntVectorIterator  != myIntVector.begin())
{
      
	--myIntVectorIterator ;
	cout << (*myIntVectorIterator )<< "\n";
}




    system("pause");
    return 0;
}

Edited by wazzer225: n/a

3
Contributors
2
Replies
3
Views
6 Years
Discussion Span
Last Post by mitrmkar
1

The "end" of the vector is not actually a value you've inserted but more of a marker. This is why you would use, for example, for(myIterator = vector.begin(); myIterator != vector.end(); ++myIterator) The "begin" points to the first item in the vector, however, the "end" does not point to any valid item you have inserted. You would need to point to "end - 1" effectively.

1

>> I'm trying to iterate backwards through a vector.

Consider using a reverse iterator, for an example, have a look at vector::rbegin().

Votes + Comments
Good idea. Not something you need very often, but very useful when you do.
This topic has been dead for over six months. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.