Skip to content

Instantly share code, notes, and snippets.

@Camerash
Created May 8, 2018 17:03
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Camerash/703a41d2c1f748b84aa2cc62554b0784 to your computer and use it in GitHub Desktop.
Save Camerash/703a41d2c1f748b84aa2cc62554b0784 to your computer and use it in GitHub Desktop.
SmartArray add function
template <typename KeyType, typename ValueType>
bool SmartArray<KeyType, ValueType>::add(KeyType key, ValueType value) {
if(has(key)) return false;
// Init a bigger pointer array
Pair<KeyType, ValueType>** newData = new Pair<KeyType, ValueType>*[size+1];
if(size == 0) {
newData[0] = new Pair<KeyType, ValueType>(key, value);
} else {
// Copy + insert
bool inserted = false;
for (int i = 0; i < size; i++) {
if (inserted) {
newData[i + 1] = data[i];
} else {
// is last element or smaller than the next
if (data[i]->key > key) {
newData[i] = new Pair<KeyType, ValueType>(key, value);
newData[i + 1] = data[i];
inserted = true;
} else if (i + 1 == size) {
newData[i] = data[i];
newData[i + 1] = new Pair<KeyType, ValueType>(key, value);
inserted = true;
} else {
newData[i] = data[i];
}
}
}
}
// Delete the old pointer array
delete [] this->data;
this->data = newData;
this->size += 1;
return true;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment