Dynamic lists: .end() not working

Hi guys!

I am working with dynamic lists. I found that if you have inserted (.push_back) an object at the end of the list and you try to get the iterator of that position (.end), the program doesn´t work fine. However, if you insert the object at the beginning (.push_front), you can get the iterator (.begin) without any problem.
Is there any bug with .end?

Thank you in advance

This code works fine:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
list<figura> load (const list<list<string>>& data){
	list<list<string>>::const_iterator iterdataext;
	list<string>::const_iterator iterdataint;
	figura fig; line lin; arc ar;
	list<figura> figuras;
	list<figura>::iterator iterfig;

	for(iterdataext = data.begin(); iterdataext != data.end(); ++iterdataext){
		iterdataint = (*iterdataext).begin();
		if (...) {
			figuras.push_front(fig);
			iterfig=figuras.begin();
			fig.name.clear(); fig.lines.clear(); fig.arcs.clear();
		}
		fig.name = (*iterdataint);
		++iterdataint;
		if ((*iterdataint) == "Line"){...}
		else if ((*iterdataint) == "Arc"){...}
		else{...}
	}
figuras.push_front(fig);
return figuras;
}


This code doesn´t work
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
list<figura> load (const list<list<string>>& data){
	list<list<string>>::const_iterator iterdataext;
	list<string>::const_iterator iterdataint;
	figura fig; line lin; arc ar;
	list<figura> figuras;
	list<figura>::iterator iterfig;

	for(iterdataext = data.begin(); iterdataext != data.end(); ++iterdataext){
		iterdataint = (*iterdataext).begin();
		if (...) {
			figuras.push_back(fig); //CHANGE
			iterfig=figuras.end(); //CHANGE
			fig.name.clear(); fig.lines.clear(); fig.arcs.clear();
		}
		fig.name = (*iterdataint);
		++iterdataint;
		if ((*iterdataint) == "Line"){...}
		else if ((*iterdataint) == "Arc"){...}
		else{...}
	}
figuras.push_back(fig); //CHANGE
return figuras;
}
Last edited on
end() returns an iterator to one PAST the last element in the list:

1
2
3
4
5
6
7
8
9
10
11
12
list<int> foo;

foo.push_back(1);
foo.push_back(15);
foo.push_back(9);

/*
[1] - [15] - [9] - [x]
 ^                  ^
 |                  |
 |                  end
 begin */


attempting to dereference end() is bad because end never refers to a valid element.

It works this way for all STL containers.
Thank you for the reply.
You nailed it, that was exactly the reason of the problem.
I realized that the .end way can work decrementing the iterator.
 
iterfig=figuras.end(); --iterfig;
That's not the correct way to find the last element.
The past-the-end element is the theoretical element that would follow the last element in the list container. It does not point to any element, and thus shall not be dereferenced.


If you want to reference the last element, you should use rbegin() (reverse begin).
http://www.cplusplus.com/reference/list/list/rbegin/


Topic archived. No new replies allowed.