2016-12-10 7 views
-3
#include <iostream> 
#include <cstddef> 

template <typename T> 
class list 
{ 
    struct Node 
    { 
     T data; 
     Node* next; 
     Node(T d, Node* n) 
      : data(d), next(n) 
     {} 
    }; 

    Node* head; 

public: 
    list() 
     : head(nullptr) 
    {} 

    void push_front(T d) 
    { 
     head = new Node(d, head); 
    } 

    class iterator 
    { 
     Node* current; 

    public: 
     typedef T value_type; 

     iterator(Node* init = nullptr) 
      : current(init) 
     { 
//   std::cout<<"init iterator"<<std::endl; 
//   std::cout<<current->data<<std::endl; 
     } 


     iterator& operator++() 
     { 
      current = current->next; 
      return *this; 
     } 

     T& operator*() 
     { 
      current->data; 
     } 

     bool operator!=(const iterator& i) 
     { 
      return (current != i.current); 
     } 

     bool operator==(const iterator& i) 
     { 
      return (current == i.current); 
     } 
    }; 

    iterator begin() 
    { 
     return iterator(head); 
    } 

    iterator end() 
    { 
     return iterator(nullptr); 
    } 

}; 

int main(void) 
{ 

    list<int> a; 
    for(int i = 1; i<=10; ++i) { 
     a.push_front(i); 
    } 

    for(auto it = a.begin(); it != a.end(); ++it) { 
     std::cout<<*it<<std::endl; 
    } 

    return 0; 
} 

出力:C++私は知らない

 
15393072 
15393040 
15393008 
15392976 
15392944 
15392912 
15392880 
15392848 
15392816 
15392784 

"a.push_front(I);"大丈夫ですか?

でも、反復子が間違っている可能性があります。 なぜこのコードが間違っていますか?

〜私を助けて、私はC++ 14コンパイラを使用して、Linuxの

+0

あなたの演算子*リターン参照解決

T& operator*() { return current->data; } 

、すべてでなければなりません。 –

+1

(引用符で囲まれていない部分をコードのように見せないようにするには、それらをブロック引用符で囲んでください)観察された振る舞いを表示します:何が_required behaviour_ですか?) – greybeard

答えて

0
T& operator*() 
    { 
     current->data; 
    } 

は、データT&へ〜

+0

haha​​ha ..........ありがとうD なぜコンパイルが完了したのですか? – naig

+0

なぜコンパイルが完了したのですか? – Jiahao

関連する問題