1: // Created by Frank M. Carrano and Timothy M. Henry. 2: // Copyright (c) 2017 Pearson Education, Hoboken, New Jersey. 4: template <class KeyType, class ValueType> 5: bool ArrayDictionary<KeyType, ValueType>::add(const KeyType& searchKey, 6: const ValueType& newValue) 7: throw(PrecondViolatedExcept) 8: { 9: bool ableToInsert = (itemCount < maxItems); 10: if (ableToInsert) 11: { 12: // Make room for new entry by shifting all entries at 13: // positions >= newPosition toward the end of the array 14: // (no shift if newPosition == itemCount + 1). Performing 15: // a binary search doesn't help here, because we need to 16: // shift the entries while looking for the location of the addition. 17: int index = itemCount; 18: 19: // Short-circuit evaluation is important 20: while ( (index > 0) && (searchKey < items[index – 1].getKey()) ) 21: { 22: items[index] = items[index–1]; 23: index--; 24: } // end while 25: 26: // Enforce precondition: Ensure distinct search keys 27: if (searchKey != items[index – 1].getKey()) 28: { 29: // Insert new entry 30: items[index] = Entry<KeyType, ValueType>(searchKey, newValue); 31: itemCount++; // Increase count of entries 32: } 33: else 34: { 35: auto message = "Attempt to add an entry whose search key exists in dictionary."; 36: throw(PrecondViolatedExcept(message)); 37: } // end if 38: } // end if 39: 40: return ableToInsert; 41: } // end add