手写Vector和注意事项

2021/5/1 18:29:26

本文主要是介绍手写Vector和注意事项,对大家解决编程问题具有一定的参考价值,需要的程序猿们随着小编来一起学习吧!

本来写了一个还可以版本的Vector,然后改了一下用迭代器,然后就从2点查到5点。。。。

#pragma once
#include <string.h>
#include <assert.h>
template<class T>
class Vector {
	typedef T* iterator;
	iterator _begin, _final;
	int _capacity;
public:
	Vector():_begin(nullptr),_final(nullptr),_capacity(0) {

	}
	~Vector() {
		delete[]_begin;
		_begin = nullptr;
		_final = nullptr;
	}
	Vector( Vector<T>& t) {
		_begin = t._begin;
		_final = t._final;
		for (int i = 0; i < t.size(); i++) {
			_begin[i] = t[i];
		}
	}
	void resize(int tocapcity) {
		T* newp = new T[tocapcity];
		for (int i = 0; i < size(); i++) {
			newp[i] = _begin[i];
		}
		int _size = size();//防止被污染
		_begin =newp;
		_final = _begin + _size;
		_capacity = tocapcity;
		newp = nullptr;
	}
	void push_back(int i) {
		if (size() == capacity()) {
			capacity() == 0 ? resize(2) : resize(2 * _capacity);
		}
		*(_final++) = i;
	}
	
	int size() const{
		return _final - _begin;
	}
	T& operator [](int i) {
		assert(i >= 0 && i <size());
		return _begin[i];
	}
	T& operator [](int i) const {
		assert(i >= 0 && i <= size());
		return _begin[i];
	}
	bool operator ==(const Vector<T>& v) {
		bool flag = true;
		if (v.size() == size()) {
			for (int i = 0; i < size(); i++) {
				if ( _begin[i]!=v[i]) {
					flag = false;//只有size相同并且全字匹配才return true
					break;
				}
			}
			return flag;
		}
		else {
			return false;
		}
	}
	iterator& begin() {
		assert(!empty());
		return  _begin;
	}
	iterator& Back() {
		assert(!empty());
		return _final;
	}
	int capacity() {
		return _capacity;
	}
	void clear() {
		_begin=nullptr;
		_final =nullptr;
	}
	bool empty() {
		return _final ==_begin;
	}
	void pop_back() {
		assert(!empty());
		_final--;//emm跟stack的处理方式类似
	}
	void erase(iterator from, iterator to) {//前闭后开hh
		assert(from >= _begin && from <= to && to <= _final);
		for (iterator i = from;i<=_final-(to-from); i++) {
			*i = *(i + (to - from));
		}
		_final -=(to-from) ;
	}
	void insert(iterator pos, int num, int val) {
		assert(num > 0);
		if (size() + num > _capacity) {//一定要判断是否合法
			resize(size() + num);
		}
		for (iterator i = _final + num - 1; i >=pos+num; i--) {
			*i = *(i - num);
		}
		for (iterator i = pos; i < pos + num; i++) {
			*i = val;
		}
		_final += num;
	}
	void insert(int pos, int val) {//在pos前插入一个数字val
		insert(pos, 1, val);//委托构造
	}
	void swap( Vector<T>& t) {
		Vector temp = t;
		t = *this;
		*this = temp;
	}

};

注意事项:
1:stl源码命名都是有他的道理的,不是闲的没事用一个_来命名,这次给变量命名的时候就发现这个下划线的好处了。。。。,就是不要污染命名空间。

2.c++中对于空指针尽量使用nullptr。

3.memcpy不安全,请尽量使用memmove函数。

4.对于私有成员的使用,请尽量简练,不要出现冗余的变量,同时对于每一次的操作,记得更新class类的私有成员,否则就会因为(for instance :me),第33行的Capacity = tocapcity;查了好久。。。

5.对于重载运算符,访问数组下标等的情况,请一定检查合法性,推荐使用assert函数。

6.即便使用委托构造,也要想好时间复杂度,比如如果用insert(iterator pos,int val)去构造insert(iterator pos,int num,int val),效率就会慢于
用后者构造前者(因为从pos-final的变量移动了多次)。



这篇关于手写Vector和注意事项的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!


扫一扫关注最新编程教程