自主编写Vector类(高级数据结构)

                                           **自主编写Vector类**

作者:一名来自青海大学的硕士研究生(高级数据结构课程实验随笔)
Vector类包含的功能有如下(主人太累了,不想多解释,代码中有详细解释):
(以下代码仅供大家学习使用,大家尽量不要抄袭)

#include<iostream>
#include<cstring>
#include<time.h>
#include<stdlib.h>
#define ll long long int
#define S string
#define C char
using namespace std;
template <class T>
class vector{
	private:
		ll cnt;
	public:
		T a[1000005];
		//构造函数初始化cnt; 
		vector()
		{
			cnt=0;
		}
		//向vector容器中输入数据类型为T的x;
		void push_back(T x)				 
		{
			a[cnt]=x;
			cnt++;
		}
		//从容器的尾端移除元素 
		void pop_back()
		{
			cnt--;
		} 
		//返回vector容器中元素的个数; 
		ll size()
		{
			return cnt;
		}
		//查找元素在整个容器中第一次出现的位置,有则返回具体位置,否则返回-1(代表容器中没有该元素);
		ll findBegin(T x)					 
		{
			ll i;
			for(i=0;i<cnt;i++)
			{
				if(a[i]==x)
				{
					return i+1;
				}
			}
			if(i==cnt)
			{
				return -1;
			} 
		}
		//从整个容器末尾开始查找第一个出现的位置,有则返回具体位置,否则返回-1(代表容器中没有该元素);
		ll findEnd(T x)					 
		{
			ll i;
			for(i=cnt-1;i>=0;i--)
			{
				if(a[i]==x)
				{
					return i+1;
				}
			}
			if(i==-1)
			{
				return -1;
			}
		}
		//查找元素在整个容器中出现的次数,有则返回出现的个数,否则返回0(代表容器中没有该元素); 
		ll findCount(T x)
		{
			ll num=0,i;
			for(i=0;i<cnt;i++)
			{
				if(a[i]==x)
				{
					num++;
				}
			}
			if(i==cnt&&num==0)
			{
				return 0;
			}
			else
			{
				return num;
			}
		}
		//对于顺序元素的查找法:二分查找,有则返回具体位置,否则返回-1(代表容器中没有该元素);
		ll search(T x)
		{
			ll l=0,r=cnt-1,h;
			while(l<=r)
			{
				h=(l+r)/2;
				if(a[h]==x)
				{
					return h+1;
				}
				else
				{
					if(a[h]<x)
					{
						l=h+1;
					}
					else
					{
						r=h-1;
					}
				}
			}
			if(l>r)
			{
				return -1;
			}
		}
		//有序表中去重操作 
		void unique()
		{
			ll i,count=0;
			for(i=1;i<cnt;i++)
			{
				if(a[i]==a[i-1])
				{
					removeDestination(i);
					i--;
				}
			}
		}
		//无序表中去重操作
		void disorderUnique()
		{
			ll i;
			for(i=0;i<cnt;i++)
			{
				removeExcepteBegin(a[i]);
				
			}
		} 
		//插入元素操作 
		void insert(ll dest,T x)
		{
			ll i;
			cnt++;
			for(i=cnt;i>=dest;i--)
			{
				a[i]=a[i-1];
			}
			a[dest-1]=x;
		}
		//移除位置在dest位置的元素 
		T removeDestination(int dest)
		{
			ll i;
			T value;
			value=a[dest-1];
			for(i=dest-1;i<cnt;i++)
			{
				a[i]=a[i+1];
			}
			cnt--;
			return value;
		}
		//移除从整个容器开头开始向后查询x第一次出现的位置并删除这个位置的元素;
		void removeBeginDiscover(T x)
		{
			ll dest=findBegin(x),i;
			if(dest!=-1)
			{
				for(i=dest;i<cnt;i++)
				{
					a[i-1]=a[i];
				}
				cnt--;
			}
		}
		//移除从整个容器结尾开始向前查询x第一次出现的位置并删除这个位置的元素;
		void removeEndDiscover(T x)
		{
			ll dest=findEnd(x),i;
			if(dest!=-1)
			{
				for(i=dest;i<cnt;i++)
				{
					a[i-1]=a[i];
				}
				cnt--;
			}
		}
		//移除容器中所有x元素 
		void removeAll(T x)
		{
			ll destBegin=findBegin(x),destEnd=findEnd(x),i;
			for(i=destBegin-1;i<
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值