c ++中指针列表中的最后一个元素

use*_*449 3 c++ pointers stl list

这是一段简单的代码,它给了我错误的输出,但我无法弄清楚为什么.

#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.
    l.push_back(y);
    cout << **l.end() << endl;   // not 7
}
Run Code Online (Sandbox Code Playgroud)

我该如何解决?

999*_*99k 8

.end()返回一个迭代器,引用列表容器中的past-the-end元素.过去的结束元素是跟随列表容器中最后一个元素的理论元素.它没有指向任何元素,因此不应被解除引用.

使用frontback成员函数

cout << *l.front() << endl;   
cout << *l.back() << endl;
Run Code Online (Sandbox Code Playgroud)

检查此链接