2013-04-02 52 views
3

這是一段簡單的代碼,它給了我錯誤的輸出,但是我找不到原因。C++中指針列表的最後一個元素

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

我該如何解決?

+1

'空隙main'是非標準和'l.end()'並在不是 「點」 在特定的任何地方提領感。 – chris

回答

8

.end()返回引用列表容器中過去結束元素的迭代器。過去結束元素是將遵循列表容器中最後一個元素的理論元素。它不指向任何元素,因此不應被解除引用。

使用frontback成員函數

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

Check this link

相關問題