您的位置:首页 > 其它

shared_ptr使用,构建list

2013-09-10 16:01 232 查看
节点类:

/**
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;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: