Unable to print first element(in reverse)

Hello, once again,
This is kind of an ultra newbie question, but here it goes: Why can't I print the first element inside my list using this kind of for loop that goes in reverse:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
#include <iostream>
#include <list>

using std::string;
using std::cout;
using std::cin;
using std::endl;

int main() {
	int arr[] = {1, 2, 3};
	std::list<int> ilist(arr, arr + sizeof(arr)/sizeof(int));
	std::list<int>::iterator j = ilist.end();
	--j;
	for(std::list<int>::iterator i = ilist.begin(); j != i; --j) {
		cout << *j << "\t";
	}
    return 0;
}


That code above will only print: 3 2
My goal is to get it to print: 3 2 1

Help me once again please, I can't seem to see why it won't print the first position.
Thank you,
Last edited on
Your loop will exit when j reaches begin(), which points to the first element. So it will never be printed.
You should use a reverse iterator instead:
for(std::list<int>::reverse_iterator it=ilist.rbegin();it!=ilist.rend();++it)cout << *it << "\t";
GREAT !

I forgot about the existence of the magical reverse iterators !

Thank you Athar !

I'm so happy that I'm learning so much.

Best Regards,

Jose
Topic archived. No new replies allowed.