Marcus Lee / LinearArray

linearArray.hpp

Committer:
UHSLMarcus
Date:
2017-03-14
Revision:
9:68d882e457c5
Parent:
2:92576523c23e
Child:
10:864b79e79ca8

File content as of revision 9:68d882e457c5:

template<class type>
LinearArray<type>::LinearArray(int size, bool forced) :
		_elem_count(0), _array_size(size), _front(0), _rear(-1), _forced(forced) {
	_array = new (std::nothrow) type[size];
}

template<class type>
LinearArray<type>::~LinearArray() {
	delete[] _array;
}

template<class type>
int LinearArray<type>::push(type item) {

	int ret = -1;
	bool room = _elem_count < _array_size;
	if (!room && _forced) {
		if (++_front == _array_size) _front = 0;
		_elem_count--;
		room = true;
	}
	if (room) {
		if (_rear == _array_size - 1) _rear = -1;
		_array[++_rear] = item;
		ret = _elem_count++;
	}

	return ret;
}

template<class type>
type& LinearArray<type>::pop() {

	static type defaultType;
	type item = defaultType;

	if (_elem_count > 0) {
		item = _array[_front++];
		if (_front == _array_size) _front = 0;
		_elem_count--;
	}

	return item;

}

template<class type>
bool LinearArray<type>::try_pop(type& item) {
	bool success = false;

	if (_elem_count > 0) {
		item = _array[_front++];
		if (_front == _array_size) _front = 0;
		_elem_count--;
		success = true;
	}

	return success;
}

template<class type>
type& LinearArray<type>::peek(int idx) {

	static type defaultType;
	type item = defaultType;

	if (idx <= _elem_count) {
		int real_loc = _front + idx;
		if (real_loc >= _array_size) {
			real_loc = real_loc - _array_size;
		}

		item = _array[real_loc];
	}

	return item;

}

template<class type>
int LinearArray<type>::size() {
	return _array_size;
}

template<class type>
int LinearArray<type>::count() {
	return _elem_count;
}

template<class type>
bool LinearArray<type>::full() {
	return _elem_count == _array_size;
}