吾爱破解 - LCG - LSG |安卓破解|病毒分析|www.52pojie.cn

 找回密码
 注册[Register]

QQ登录

只需一步,快速开始

查看: 1203|回复: 1
收起左侧

[C&C++ 转载] 以前学习STL时练手写的一个简陋版vector

[复制链接]
htpidk 发表于 2020-11-16 20:19
无意中翻到以前学习STL时练手写的简陋版vector,只实现了push_back  pop_back begin end等方法,其他的方法没有写
[C++] 纯文本查看 复制代码
#include <iostream>
using namespace std;


template<typename T>
class Myarray{
	public:
		Myarray();
		void push_back(T);
		void pop_back();
		T operator [](int);
		typedef T* iterator;
		iterator begin();
		iterator end();//返回值是指向最后一个元素后面的位置,而不是指向最后一个元素的位置 
	private:
		T* pt;
		int currentcount;
		int maxcount;
};

template<typename T>
Myarray<T>::Myarray(){
	pt=new T[10];
	currentcount=0;
	maxcount=10;
}

template<typename T>
void Myarray<T>::push_back(T kt){
	if(currentcount<maxcount){
		pt[currentcount]=kt;
		++currentcount;
	}else{
		T* tempt=new T[2*maxcount];
		memcpy(tempt,pt,currentcount*sizeof(T));
		tempt[currentcount]=kt;
		delete[] pt;
		pt=tempt;
		++currentcount;
		maxcount*=2;
	}
}

template<typename T>
void Myarray<T>::pop_back(){
	--currentcount;
}

template<typename T>
T Myarray<T>::operator [](int n){
	return pt[n];
}

template<typename T>
typename Myarray<T>::iterator Myarray<T>::begin(){
	return pt;
}

template<typename T>
typename Myarray<T>::iterator Myarray<T>::end(){
	return pt+currentcount;
}



int main(int argc, char** argv) {
	Myarray<int> ceshi;
	for(int i=0;i<10;++i)
		ceshi.push_back(i);
	for(Myarray<int>::iterator i=ceshi.begin();i!=ceshi.end();++i){
		cout<<*i<<endl;
	}
	cout<<"==================="<<endl;
	for(int i=0;i<10;++i)
		ceshi.push_back(i*2);
	for(Myarray<int>::iterator i=ceshi.begin();i!=ceshi.end();++i){
		cout<<*i<<endl;
	}
	cout<<"==================="<<endl;
	ceshi.pop_back();
	for(Myarray<int>::iterator i=ceshi.begin();i!=ceshi.end();++i){
		cout<<*i<<endl;
	}
	cout<<"==================="<<endl;
	cout<<"测试[]重载"<<"\t"<<ceshi[5]<<endl;
	cout<<"==================="<<endl;
	
	Myarray<char*> cschar;
	cschar.push_back("ceshi");
	cschar.push_back("水电费");
	cschar.push_back("234");
	cschar.push_back("sdf333");
	cschar.push_back("参数df3");
	for(Myarray<char*>::iterator i=cschar.begin();i!=cschar.end();++i){
		cout<<*i<<endl;
	}
	cout<<"==================="<<endl;
	cschar.pop_back();
	for(Myarray<char*>::iterator i=cschar.begin();i!=cschar.end();++i){
		cout<<*i<<endl;
	}
	cout<<"==================="<<endl;
	
	system("pause");
	return 0;
}

捕获.PNG

免费评分

参与人数 1吾爱币 +5 热心值 +1 收起 理由
苏紫方璇 + 5 + 1 欢迎分析讨论交流,吾爱破解论坛有你更精彩!

查看全部评分

发帖前要善用论坛搜索功能,那里可能会有你要找的答案或者已经有人发布过相同内容了,请勿重复发帖。

zhaomingzhi 发表于 2020-11-16 21:08
大佬大佬
您需要登录后才可以回帖 登录 | 注册[Register]

本版积分规则 警告:本版块禁止灌水或回复与主题无关内容,违者重罚!

快速回复 收藏帖子 返回列表 搜索

RSS订阅|小黑屋|处罚记录|联系我们|吾爱破解 - LCG - LSG ( 京ICP备16042023号 | 京公网安备 11010502030087号 )

GMT+8, 2024-5-2 21:58

Powered by Discuz!

Copyright © 2001-2020, Tencent Cloud.

快速回复 返回顶部 返回列表