Created
September 22, 2019 19:47
-
-
Save danielgospodinow/43d5f7550581c3e32435ad869c51fcb2 to your computer and use it in GitHub Desktop.
ArrayList removeAt operation
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* Remove an element from a specified index. | |
* | |
* @tparam T type | |
* @param index index of an element | |
*/ | |
template<typename T> | |
void ArrayList<T>::removeAt(const int index) { | |
if (index < 0 || index >= _size) { | |
// If the index is out of bounds, throw an exception. | |
throw std::invalid_argument("Index out of bounds"); | |
} else { | |
// Shift all elements from the provided index up to the last one | |
// with one position to the left. | |
for (int i = index; i < _size - 1; ++i) { | |
_array[i] = _array[i + 1]; | |
} | |
// Reduce the size of the data structure. | |
--_size; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment