Untitled

mail@pastecode.io avatar
unknown
plain_text
2 years ago
1.2 kB
1
Indexable
Never
#define _CRT_SECURE_NO_WARNINGS

#include <cstdio>
#include <iostream>
#include <cstdlib>
using namespace std;



template <class T>

class Sqlist {
private:
	T* data;
	int capacity, n;
    bool realloc();
	

public:
	Sqlist(int cap = 100) {
		T* data =new T[cap];
		if (!data) throw "内存分配失败";
		capacity = cap; n = 0;
	}

	bool insert(int i, T e);
	bool remove(int i);
	bool push_back(T e);
	bool insert_front(T e);
	bool get_item(int i, T& e);
	bool set_item(int i, T e);
	int size() {
		return n;
	}
	void Print() {
		for (int i = 0; i < n; i++) printf("%d ", data[i]);
		cout << endl;
	}
	
	~Sqlist(){}




};


template <class T>

bool Sqlist<T>::realloc() {
	T* new_data = new T[2 * capacity];
	if (!new_data) return false;
	capacity *= 2;


	// copy
	for (int i = 0; i < n; i++) new_data[i] = data[i];
	delete[]data;
	data = new_data;
	return true;

}



template <class T>

bool Sqlist<T>::push_back(T e) {
	if (n >= capacity) {
		if (!realloc()) return false;
	}
	data[n] = e;
	n++;
	return true;
}


void test1() {
	Sqlist<char> list(20);
	list.push_back('a');
	
	list.push_back('b');
	list.push_back('c');
	list.Print();
	
}


int main() {
	
	test1();
	return 0;
}