C++

线性表的顺序实现-Vector

Vector:The implementation of list

Posted by xuepro on September 7, 2018

线性表只使用最广泛的一种数据结构。这是“C+++17从入门到精通”书中仿“雷电战机”游戏里用到的一个小代码片段。 这个类理解了,那么就能理解C++的std::vector类模板的实现原理了!


using ElemType = int;

class Vector {

	ElemType *data{ nullptr };
	int  capacity{ 0 }, n{ 0 };
public:
	Vector(const int cap = 5) :capacity{ cap }, data{ new ElemType[cap] }
	{}
  
	bool insert(const int i, const ElemType &e) {
		if (i < 0 || i >= n) return false;
		if (n == capacity && !add_capacity())
			return false;
		for (auto j = n; j > i; j--)
			data[j] = data[j - 1];
		data[i] = e;
		return true;
	}
  
	bool erase(const int i) {
		if (i < 0 || i >= n) return false;
		for (auto j = i; j < n - 1; j++)
			data[j] = data[j + 1];
		n--;
		return false;
	}
  
	bool push_back(const ElemType &e) {
		if (n == capacity && !add_capacity())
			return false;
		data[n++] = e;
		return true;
	}
  
	bool pop_back(const ElemType e) {
		if (n == 0) return false;
		n--; return true;
	}

	ElemType get(const int i)const {
		if (i >= 0 && i < n)
			return data[i];
		throw "下标非法!\n";
	}
  
	ElemType get(const int i, const ElemType &e)const {
		if (i >= 0 && i < n)
			return data[i] = e;
	}

	ElemType& operator[](int i) {
		if (i >= 0 && i < n) return data[i];
		else throw "下标非法";
	}
  
	ElemType operator[](const int i) const {
		if (i >= 0 && i < n) return data[i];
		else throw "下标非法";
	}

	bool add_capacity() {
		ElemType *temp = new ElemType[2 * capacity];
		if (!temp) return false;
		for (auto i = 0; i < n; i++) {
			temp[i] = data[i];
		}
		delete[] data;
		data = temp; capacity *= 2;
		return true;
	}

	int size() const { return n; }
};


#include <iostream>

int main() {

	Vector v(2);
	v.push_back(2);
	v.push_back(3);
	v.push_back(4);
	v.push_back(5);
	v[1] = 11;
	for (int i = 0; i < v.size(); i++)
		std::cout << v[i] << '\t';
	std::cout << std::endl;
	v.erase(2);
	for (int i = 0; i < v.size(); i++)
		std::cout << v[i] << '\t';
	std::cout << std::endl;
	v.erase(2);
	for (int i = 0; i < v.size(); i++)
		std::cout << v[i] << '\t';
	std::cout << std::endl;
}



支付宝打赏 微信打赏

您的打赏是对我最大的鼓励!