如何处理模板返回?
问题描述:
也许是因为我是一个新手,无法定义它属于哪种类型的问题。所以在搜索后我没有找到想要的结果。如何处理模板返回?
这是我的链接列表实现与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来停止这个程序。处理这种情况的方式有没有更多的方法?
答
我会改变函数签名
bool showKey(int n, T& value);
,并用它来设置变量的值,如果一个条目,为指数n存在返回true,并返回false(离开价值不变),如果进入不存在。
答
你最好的选择很可能是抛出异常; std::domain_error
或std::range_error
可能是合适的。
抛出异常? – chris 2014-10-10 03:02:07
创建一个代表“未找到”的卓越“T”。或者返回一个迭代器。 – jww 2014-10-10 03:04:43
如果'n'大于列表中的项目数,此行'temp = temp-> next;'将取消引用NULL指针。 – 2014-10-10 03:41:44