设为首页 加入收藏

TOP

STL,迭代器的C++简单实现(一)
2014-11-24 07:27:14 】 浏览:3680
Tags:STL 简单 实现
[cpp]
// Iterator.cpp : 定义控制台应用程序的入口点。
//
#include "stdafx.h"
#include
#include
#include
#include
using namespace std;
// 对于C++,STL中已经包含迭代器的实现了
// 就不再单独造车轮了
// 部分代码见【STL 源码剖析】
// 来一个智能指针的示意
namespace TEST
{
template
class auto_ptr
{
public:
// 显示构造函数
explicit auto_ptr(T *p = NULL) : pointee(p){}
template
auto_ptr(auto_ptr& rhs) : pointee(rhs.release()){}
~auto_ptr() {delete pointee;}
template
auto_ptr& operator=(auto_ptr& rhs)
{
if (this != &rhs)
{
reset(rhs.release());
return *this;
}
}
T& operator*() const
{
return *pointee;
}
T* operator->() const
{
return pointee;
}
T* get() const
{
return pointee;
}
protected:
T* release()
{
T *p = new T;
memcpy(p, pointee, sizeof(T));
delete this;
return p;
}
void reset(T *p)
{
if (pointee)
{
delete pointee;
pointee = NULL;
}
pointee = p;
}
private:
T *pointee;
};
}
// 智能指针的示例
// 申请的内存不需要释放,没有内存泄露
void func()
{
TEST::auto_ptr ps(new string("Hello"));
cout<< *ps <
cout<< ps->size() <
}
namespace TEST
{
template
class ListItem
{
public:
ListItem(T vl)
: _value(vl)
, _next(NULL)
{
}
T value() const {return _value;}
ListItem *next() const {return _next;}
void SetNext(ListItem *p){_next = p;}
private:
T _value;
ListItem *_next;
};
// 迭代器是一种智能指针
template
class List
{
public:
List()
{
ListItem *a = new ListItem(0); // 没有析构哦
_front = a;
_front->SetNext(NULL);
_size = 0;
}
void insert_end(T value);
void display(std::ostream &os = std::cout) const;
ListItem * front(){return _front;}
ListItem * end()
{
ListItem *end = _front;
while(1)
{
if (end->next())
{
end = end->next();
}
else
{
break;
}
}
return end;
}
private:
ListItem *_front;
long _size;
};
template
void TEST::List::display( std::ostream &os /*= std::cout*/ ) const
{
ListItem *end = NULL;
end = _front->next();
ListItem *before = _front;
do
{
os<value()<
end = end->next();
} while (end);
}
// 因为只保留了链表头,所以插入操作很纠结,比较失败
template
void TEST::List::insert_end( T value )
{
ListItem *node = new ListItem(value);
ListItem *end = this->end();
//end = _front;
//while(1)
//{
// if (end->next())
// {
// end = end->next();
// }
// else
// {
// break;
// }
//}
end->SetNext(node);
_size ++;
}
template
struct ListIter
{
Item *ptr;
ListIter(Item *p = NULL)
: ptr(p)
{
}
首页 上一页 1 2 下一页 尾页 1/2/2
】【打印繁体】【投稿】【收藏】 【推荐】【举报】【评论】 【关闭】 【返回顶部
上一篇特殊按键--休眠键驱动 下一篇2-4动态列表

最新文章

热门文章

Hot 文章

Python

C 语言

C++基础

大数据基础

linux编程基础

C/C++面试题目