【问题标题】:Last Element from List of pointers in c++c++中指针列表中的最后一个元素
【发布时间】:2013-04-02 03:50:24
【问题描述】:

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

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

我该如何解决?

【问题讨论】:

  • void main 是非标准的,l.end() 并没有“指向”任何地方,特别是在解除引用的意义上。

标签: c++ list pointers stl


【解决方案1】:

.end() 返回一个迭代器,该迭代器引用列表容器中的最后一个元素。最后一个元素是列表容器中最后一个元素之后的理论元素。它不指向任何元素,因此不应被取消引用。

使用frontback 成员函数

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

Check this link

【讨论】:

    猜你喜欢
    • 2017-12-17
    • 1970-01-01
    • 1970-01-01
    • 2023-03-04
    • 1970-01-01
    • 2010-11-13
    • 2018-12-12
    • 1970-01-01
    • 2022-01-07
    相关资源
    最近更新 更多