user2234449 user2234449 - 2 months ago 13
C++ Question

Last Element from List of pointers in c++

Here is a simple piece of code that is giving me the wrong output but I can't figure out why.

#include <iostream>
#include <list>
using namespace std;

void main(){
list<int*> l;
int x = 7;
int* y = &x;
//it works if I put list<int*> l; on this line instead.
cout << **l.end() << endl; // not 7

How can I fix it?


.end() returns an iterator referring to the past-the-end element in the list container.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.

use front or back member functions

cout << *l.front() << endl;   
cout << *l.back() << endl;

Check this link