shared_ptr使用,构建list

来源:互联网 发布:asp net入门 vb 编辑:程序博客网 时间:2024/06/08 06:09

节点类:

/**link list node**/#ifndef NODE__H__#define NODE__H__#include <memory>template<typename T>class node{public:T val;std::shared_ptr<node> next;public:node(){next.reset();}explicit node(const T& t){val=t;next.reset();}};#endif

list类:

#ifndef list_h__#define list_h__#include "node.h"#include <memory>template<typename T>class list{public:list(){head.reset();tail.reset();node_null.reset();}void push_back(const T& val){if(head==node_null){head=std::shared_ptr<node<T> >(new node<T>(val));tail=head;}else{tail->next=std::shared_ptr<node<T> >(new node<T>(val));tail=tail->next;}}T front(){return *head;}T back(){return *tail;}std::shared_ptr<node<T> >begin(){return head;}private:std::shared_ptr<node<T> > head;std::shared_ptr<node<T> > tail;public:std::shared_ptr<node<T> > node_null;};#endif


测试:

#include "list.h"#include "node.h"#include <iostream>int main(int argc,char* argv[]){list<int> l;l.push_back(23);l.push_back(2);auto t=l.begin();while(t!=l.node_null){std::cout<<t->val<<std::endl;t=t->next;}system("PAUSE");return 0;}