Skip to content

Instantly share code, notes, and snippets.

@danielgospodinow
Last active September 22, 2019 19:49
Show Gist options
  • Save danielgospodinow/a2526168030978a051cea34356549117 to your computer and use it in GitHub Desktop.
Save danielgospodinow/a2526168030978a051cea34356549117 to your computer and use it in GitHub Desktop.
Array List insert operation
/**
* Insert an element to the data structure at a specified index.
*
* @tparam T type
* @param item item to insert
* @param index index at which to insert
*/
template<typename T>
void ArrayList<T>::insert(const T &item, 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 {
// Check if there's a need to make additional space.
if (_size >= _capacity) {
resize();
}
// Increase the size of the data structure.
// Note: It's important to do this here, before the for-loop
// below, because the loop needs to shift some elements with one
// position to the right.
++_size;
// Shift all elements from the end down to the provided index
// with one position to the right.
for (int i = _size - 1; i > index; --i) {
_array[i] = _array[i - 1];
}
// Assign the new element.
_array[index] = item;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment