其他分享
首页 > 其他分享> > 自实现简易vector中的iterator迭代器

自实现简易vector中的iterator迭代器

作者:互联网

【头文件】

// MyVector.h
#ifndef MYVECTOR_H
#define MYVECTOR_H

#include <iostream>
using namespace std;

template <class T>
class MyVector {
private:
	T* data;  //指针数组存放数据
	size_t Size;  //记录数组大小
	size_t Capacity;  //记录数组容量
public:
	MyVector() {
		Size = 0;
		Capacity = 100;  //初始默认容量为100
		data = new T[Capacity];
	}
	~MyVector() {
		Size = Capacity = 0;
		delete[]data;
		data = nullptr;
	}
	//重载下标运算
	T operator [] (const unsigned int index) {
		return data[index];
	}
	void push_back(const T m_data) {
		if (Size == Capacity) {  //数组扩容
			T* tmp = new T[Capacity * 2];
			memcpy(tmp, data, Capacity * sizeof(T));  //将原数据拷贝到新建空间
			delete data;  //删除原空间
			data = tmp;
			Capacity *= 2;
		}
		data[Size++] = m_data;
	}
	void pop_back() { --Size; }
	size_t size() { return Size; }
	size_t capacity() { return Capacity; }
public:
	class Iterator {  //自定义迭代器
	private:
		T* it;  //一个T类型指针
	public:
		Iterator() { it = nullptr; }
		Iterator(T* m_it) { it = m_it; }
		~Iterator() { it = nullptr; }
		Iterator operator = (const Iterator m_it){
			it = m_it.it;
			return *this;
		}
		void operator ++ () { it = it + 1; }
		bool operator == (const Iterator m_it) {
			return it == m_it.it;
		}
		bool operator != (const Iterator m_it) {
			return it != m_it.it;
		}
		T operator * () { return *it; }
	};
	Iterator begin() {
		return Iterator(&data[0]);
	}
	Iterator end() {
		return Iterator(&data[Size]);
	}
};

#endif // !MYVECTOR_H

【演示文件】

//Test01.cpp
#include "MyVector.h"
using namespace std;
int main() {
	MyVector<int> v;
	for (int i = 0; i < 300; ++i) v.push_back(i);
	for (MyVector<int>::Iterator it = v.begin();it != v.end() ; ++it) {
		cout << *it << endl;
	}
	return 0;
}

【运行结果】

在这里插入图片描述

欢迎指正

CUG_YZL 发布了32 篇原创文章 · 获赞 0 · 访问量 2062 私信 关注

标签:MyVector,return,迭代,Iterator,vector,Capacity,iterator,data,Size
来源: https://blog.csdn.net/weixin_44211980/article/details/104462082