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

Last Element from List of pointers in c++

本文关键字:最后一个 元素 列表 指针 c++      更新时间:2023-10-16

这是一段简单的代码,它给了我错误的输出,但我不知道为什么。

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

我该如何修复它?

.end()返回一个指向列表容器中过尾元素的迭代器。past-the-end元素是理论上的元素,它位于列表容器中最后一个元素之后。它不指向任何元素,因此不能被解引用。

使用frontback成员函数

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

查看此链接