Created
May 8, 2018 17:03
-
-
Save Camerash/703a41d2c1f748b84aa2cc62554b0784 to your computer and use it in GitHub Desktop.
SmartArray add function
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
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