简单的自制类(包含迭代器的使用)

#include<bits/stdc++.h>
using namespace std;
struct Array_iterator{
	int *ptr;
	void operator++(){
		ptr++;
	}
	int operator*(){
		return *ptr;
	}
	bool operator!=(Array_iterator x){
		if(ptr==x.ptr)return false;
		else return true;
	}
};
struct Array{
	int *buf;
	int size;
	Array(){
		buf=NULL;
		size=0;
	}
	void push_back(int x){
		if(buf==NULL){
			buf=(int*)malloc(1);
		}
		else{
			buf=(int*)realloc(buf,size+1);
		}
		++size;
		buf[size-1]=x;
	}
	int operator[](int i){
		return buf[i];
	}
	Array_iterator begin(){
		Array_iterator it;
		it.ptr=buf;
		return it;
	}
	Array_iterator end(){
		Array_iterator it;
		it.ptr=buf+size;
		return it;
	}
};

int main(){
	Array a;
	Array_iterator it;
	a.push_back(1);
	a.push_back(1);
	a.push_back(4);
	a.push_back(5);
	a.push_back(1);
	a.push_back(4);
	for(int i=0;i<6;i++){
		printf("%d ",a[i]);
	}
	printf("\n");
	for(it=a.begin();it!=a.end();it++){
		printf("%d ",*it);
	}
	printf("\n");
	return 0;
}
posted @ 2022-04-16 13:21  计算机知识杂谈  阅读(34)  评论(0编辑  收藏  举报