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;
}

Recommended Answers

All 2 Replies

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.

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

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

commented: Good idea. Not something you need very often, but very useful when you do. +4
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.