I am wondering if the algorithm is correct that it shows for the insertAt(int, const elemType&) function for an array-based list:

template <class elemType>
void arrayListType<elemType>::insertAt
                  (int location, const elemType& insertItem)
    if (location < 0 || location >= maxSize)
        cerr << "The position of the item to be inserted "
             << "is out of range" << endl;
        if (length >= maxSize)  //list is full
            cerr << "Cannot insert in a full list" << endl;
            for (int i = length; i > location; i--)
                 list[i] = list[i - 1];   //move the elements down

            list[location] = insertItem;  //insert the item at the
                                          //specified position

            length++;     //increment the length
} //end insertAt

The test location >= maxSize at the top of the function seems like it should be location > length instead. As it is, it seems like it allows items to be inserted past the current length of the list, resulting in holes and inaccessible items. For example, if

maxSize == 10,
length == 5, and
location == 7,

it looks like the function would insert the item at list[7] and set length = 6. This would make the item at list[7] inaccessible, and list[5] and list[6] would be undefined.

If the test were location > length instead, the function would allow an item to be inserted at the end of the list (location == length) but would disallow insertions beyond the end of the list, like the example above.

Am I missing something? Thanks


can you format your code please

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, learning, and sharing knowledge.