// -*- c++ -*- #ifndef ARRAY_LIST_H #define ARRAY_LIST_H /** * A simple, resizable array list. */ template class array_list { static const size_t INITIAL_CAPACITY = 8; size_t _size; T * _data; size_t _capacity; public: array_list(); ~array_list(); size_t size(); int32_t append(T value); int32_t push(T value); bool pop(T *value); bool replace(T old_value, T new_value); int32_t index_of(T value); bool is_empty(); T* data(); T & operator[](size_t index); }; template array_list::array_list() { _size = 0; _capacity = INITIAL_CAPACITY; _data = (T *) malloc(sizeof(T) * _capacity); } template array_list::~array_list() { free(_data); } template size_t array_list::size() { return _size; } template int32_t array_list::append(T value) { return push(value); } template int32_t array_list::push(T value) { if (_size == _capacity) { _capacity = _capacity * 2; _data = (T *) realloc(_data, _capacity * sizeof(T)); } _data[_size ++] = value; return _size - 1; } template bool array_list::pop(T *value) { if (_size == 0) { return false; } if (value != NULL) { *value = _data[-- _size]; } else { -- _size; } return true; } /** * Replaces the old_value in the list with the new_value. * Returns the true if the replacement succeeded, or false otherwise. */ template bool array_list::replace(T old_value, T new_value) { int index = index_of(old_value); if (index < 0) { return false; } _data[index] = new_value; return true; } template int32_t array_list::index_of(T value) { for (size_t i = 0; i < _size; i++) { if (_data[i] == value) { return i; } } return -1; } template T & array_list::operator[](size_t index) { return _data[index]; } template bool array_list::is_empty() { return _size == 0; } template T* array_list::data() { return _data; } #endif /* ARRAY_LIST_H */