您的位置:首页 > 编程语言 > C语言/C++

简单实现c++数组,链表及其迭代器

2017-05-08 20:34 330 查看
#include<iostream>
#include<stdio.h>
#include<stdlib.h>
#include<time.h>

using namespace std;

template<class T>
class MyArray {
private:
int m_nTotalSize;
int m_nValidSize;
T* m_pData;
public:
class Iterator {
T* t;
public:
Iterator(T* t)
{
this->t = t;
}
bool operator!=(Iterator it)
{
return this->t != it.t;
}
void operator++(int)
{
this->t++;
}
T operator*()
{
return *this->t;
}
};

MyArray(int nSize = 3) {
m_pData = new T[nSize];
m_nTotalSize = nSize;
m_nValidSize = 0;
}
void Add(T value) {
int i;
if (m_nValidSize < m_nTotalSize) {
m_pData[m_nValidSize] = value;
m_nValidSize++;
}
else {
T* tempData = new T[m_nTotalSize];
for (i = 0;i < m_nTotalSize;i++) {
tempData[i] = m_pData[i];
}
delete[]m_pData;
m_nTotalSize *= 2;
m_pData = new T[m_nTotalSize];
for (i = 0;i < m_nValidSize;i++) {
m_pData[i] = tempData[i];
}
delete[]tempData;
m_pData[m_nValidSize] = value;
m_nValidSize++;
}
}
int GetSize() {
return m_nValidSize;
}
T Get(int pos) {
return m_pData[pos];
}

T* Begin()
{
return m_pData;
}

T* End()
{
return m_pData + m_nValidSize;
}

virtual ~MyArray() {
if (m_pData != NULL) {
delete[]m_pData;
m_pData = NULL;
}
}
};

template <class T>
class MyLink {
public:
struct Unit
{
T value;
Unit* next;

};

friend ostream& operator<<(ostream &os, Unit &unit)
{
os << unit.value;
return os;
}

class Iterator {
Unit* init;
public:
Iterator(Unit* init) {
this->init = init;
}
bool operator!=(Iterator& it) {
return this->init != it.init;
}
void operator++(int) {
init = init->next;
}
Unit operator*() {
return *init;
}
};

Unit* head;
Unit* tail;
Unit* prev;
public:
MyLink() {
head = tail = prev = NULL;
}

void Add(T value) {
Unit* u = new Unit();
u->value = value;
u->next = NULL;
if (head == NULL) {
head = u;
prev = u;
}
else {
prev->next = u;
prev = u;
}
tail = u->next;
}

Unit* Begin()
{
return head;
}
Unit* End() {
return tail;
}

virtual ~MyLink() {
Unit* prev = head;
Unit* next = NULL;
if (head != NULL) {
while (prev != tail)
{
next = prev->next;
delete prev;
prev = next;
}
}
}
};

template <class Init>
void display(Init start, Init end) {
cout << endl;
for (Init mid = start;mid != end;mid++) {
cout << *mid << "\t";
}
cout << endl;
}

int main() {
int i;
MyArray<int> MyArr;
MyLink<int> MyLnk;
srand(static_cast<unsigned int>(time(NULL)));
for (i = 0;i < 5;i++)
{
MyLnk.Add(rand());
}
MyLink<int>::Iterator start = MyLnk.Begin();
MyLink<int>::Iterator end = MyLnk.End();
display(start, end);

srand(static_cast<unsigned int>(time(NULL)));
for (i = 0;i < 5;i++)
{
MyArr.Add(rand());
}
MyArray<int>::Iterator start1 = MyArr.Begin();
MyArray<int>::Iterator end1 = MyArr.End();
display(start1, end1);
system("pause");
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: