1. 程式人生 > >vector向量容器的過載實現及其常見成員函式

vector向量容器的過載實現及其常見成員函式

vector的過載實現以及常見成員方法

文章目錄

1,vector定義

vector(向量)類似於陣列,它儲存具有相同資料型別的一組元素,可以從後面快速的插入和刪除元素,可以快速地隨機訪問元素。但是在序列中間插入刪除元素較慢,因為需要移動插入或刪除處後面的所有元素。

2,vector過載的實現

#include<iostream>
using namespace std;
/*
Vector  向量容器
*/
template<typename T>
class Vector
{
public:
	Vector(int size = 10)
	{
		first = new T[size];
		last = first;
		endl = first + size;
	}
	~Vector()
	{
		delete[]first;
		first = endl = last = NULL;
	}
	Vector(const Vector<T> &src)
	{
		int size = src.last - src.first;
		first = new T[src.endl - src.first];
		for (int i = 0; i < size; ++i)
		{
			first[i] = src.first[i];
		}
		last = first + size;
		endl = first + (src.endl - src.first);
	}
	Vector<T>& operator=(const Vector<T> &src)
	{
		if (this == &src)
		{
			return*this;
		}
		delete[]first;
		first = NULL;

		int size = src.last - src.first;
		first = new T[src.endl - src.first];
		for (int i = 0; i < size; ++i)
		{
			first[i]=src.first[i];
		}
		last =first+size;
		endl = first + (src.endl - src.first);
		return*this;
	}
	bool full()
	{
		return first == endl;
	}
	// 給容器末尾新增元素
	void push_back(const T &val)
	{
		if (full())
		{
			reSize();
		}
		*last++=val;
	}
	// 從末尾刪除元素
	void pop_back()
	{
		if (last == first)
		{
			return;
		}
		--last;
	}
	int size()
	{
		return last - first;
	}
	// 給Vector容器提供迭代器的實現
	class iterator
	{
	public:
		iterator(T*ptr = NULL) :_ptr(ptr){}
		//iterator(T*ptr = NULL, int pos = 0){ _ptr = _ptr + pos; }
		bool operator!=(const iterator&it)
		{
			return _ptr != it._ptr;
		}
		bool operator++()
		{
			_ptr++;
			return true;
		}
		T&operator*()
		{
			return *_ptr;
		}
		T operator[](int index)
		{
			return _ptr[index];
		}
	private:
		T*_ptr;
	};
	iterator begin(){ return iterator(first); }
	iterator end(){ return iterator(last); }
private:
	T *first; // 表陣列的起始地址
	T *last;  // 表示最後一個元素的後繼位置的地址
	T *endl;   // 末尾位置的後繼位置

	void reSize()
	{
		int len = size();
		T*tmp = new T[size()* 2];
		int i = 0;
		for (; i < len; ++i)
		{
			tmp[i] = first[i];
		}
		delete[]first;
		first = tmp;
		endl = first + len * 2;
		last = first + len;
	}

	template<typename T>
	friend ostream& operator<<(ostream &out, const Vector<T> &vec);
};
template<typename T>
ostream& operator<<(ostream &out, const Vector<T> &vec)
{
	Vector<T>::iterator it = vec.begin();
	for (; it != vec.end(); ++i)
	{
		out << *it << " ";
	}
	cout << endl;
}

int main()
{
	Vector<char>vec;
	vec.push_back('a');
	vec.push_back('b');
	vec.push_back('c'); 
	vec.push_back('d');
	vec.pop_back();
	vec.push_back('e');
	vec.push_back('f');
	vec.push_back('g');
	vec.push_back('h');


	Vector<char>::iterator it = vec.begin();
	for (; it != vec.end(); ++it)
	{
		cout << *it << " ";
	}
	cout << endl;
}

執行結果如下:在這裡插入圖片描述

3,vector常見的成員方法

在這裡插入圖片描述