2014-10-10 43 views
0

也許是因爲我是一個新手,無法定義它屬於哪種類型的問題。所以在搜索後我沒有找到想要的結果。如何處理模板返回?

這是我的鏈接列表實現與C++模板

template<class T> struct Node 
{ 
    T value; 
    Node<T>* pre; 
    Node<T>* next; 

}; 
template<class T> class Flist 
{ 
    private: 
     Node<T>* front; 
     Node<T>* end; 
     int count; 

    public: 
     Flist(); 
     ~Flist(); 
     Flist(const Flist& C_list); 
     inline void Deeply_Copy(const Flist& Copylist); 
     bool Isempty() const; 
     int Listsize() const; 
     Node<T>& Listfront()const; 
     Node<T>& Listend() const; 
     void push_front(T N); 
     void push_back(T N); 
     void del_front(); 
     void del_back(); 
     Node<T>* Listfind(T x); 
     T ShowKey(int n); 

}; 


template<class T> T Flist<T>::ShowKey(int n) 
{ 
    if (front == 0) 
     { 
      cout << "there is no element is the list.." << endl; 
      return ???; 
     } 
    Node<T>* temp = front; 
    while(n--) 
    { 
     temp = temp->next; 
    } 
    return temp->value; 

} 

功能ShowKey(INT N)我希望它返回(不只是顯示)第n個元素的值,但如果該列表是空的,我不知道該返回什麼。我不想用exit來停止這個程序。處理這種情況的方式有沒有更多的方法?

+1

拋出異常? – chris 2014-10-10 03:02:07

+2

創建一個代表「未找到」的卓越「T」。或者返回一個迭代器。 – jww 2014-10-10 03:04:43

+1

如果'n'大於列表中的項目數,此行'temp = temp-> next;'將取消引用NULL指針。 – 2014-10-10 03:41:44

回答

2

我會改變函數簽名

bool showKey(int n, T& value); 

,並用它來設置變量的值,如果一個條目,爲指數n存在返回true,並返回false(離開價值不變),如果進入不存在。

0

你最好的選擇很可能是拋出異常; std::domain_errorstd::range_error可能是合適的。