简单的成员模板实例

template<class T>
class SList {
public:
   
 SList():head_(0),size(0) {}
 
 template<class In>
 SList(In first, In last);
 void push_front(const T& val);
 void pop_front();
 T front()const;
 void reverse();
 bool empty()const;

 void show()const;

    ~SList();
private:
 struct Node {

  Node *next_;
  T el_;
 };

   Node *head_;
   int size;
};

template<class T>
template<class In>
SList<T>::SList(In first, In last):head_(0),size(0) {
 while( first != last) {
   push_front(*first++);
 }
}

template<class T>
void SList<T>::push_front(const T &val) {
    Node *newNode = new Node;
 newNode->el_ = val;
 newNode->next_ = head_;
 head_ = newNode;
 ++size;
}

template<class T>
void SList<T>::pop_front() {
    if ( !empty())
 {
        Node *p = head_;
  if (p->next_) {
      head_ = head_->next_;
   delete p;
  }
  else {
   delete head_;
   head_ = NULL;
  }

  --size;
 }
}

template<class T>
T SList<T>::front() const {

 if (!empty())
 {
  return head_->el_;
 }
}

template<class T>
bool SList<T>::empty()const {
     return 0 == size;
}

template<class T>
SList<T>::~SList() {
 while(head_) {
  Node *p = head_;
  head_ = head_->next_;
  delete p;
  --size;
 }
}

template<class T>
void SList<T>::show()const {

 Node *p = head_;
 while(p) {
  std::cout<<p->el_<<"/n";
  p = p->next_;
 }
}

#include "Temp.cpp"
#include<vector>

int _tmain(int argc, _TCHAR* argv[])
{

 int a[5] = {1,2,3,4,5};
 std::vector<double> data(a, a + 5);
 //SList<int> S(a,a + 5 );
 SList<int> S(data.begin(), data.end() );


 S.show();
 system("pause");
 return 0;
}
 

上面的Node 也可以在类的外面定义

如:

template<class T>

struct SList<T>::Node {

Node *next_;

T el_;

};

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值