void FixedVector<T>::push_back(const T& value) {
insert( size_, value ); // delegate to insert() leveraging error checking
}
template <typename T>
size_t FixedVector<T>::insert(size_t beforeIndex, const T& value) {
// to be completed
if (beforeIndex >= capacity_)
throw std::range_error("insufficient capacity");
if (beforeIndex >= size_)
throw std::range_error("index of bounds");
if ((beforeIndex > 0) && (beforeIndex < size_ - 1)) {
for (size_t i = size_; i > beforeIndex; i--) {
array_[i] = array_[i-1]; //move all elements to the right of beforeIndex
}
array_[beforeIndex] = value; //put in the empty slot
size_++;
}
Here's main cpp
1 2 3 4 5 6 7 8 9
FixedVector<int> Array1(5);
// place 1,5,10 in the array
std::cout << "FixedArray gets the elements 1, 5, 10" << std::endl;
Array1.push_back(1);
Array1.push_back(5);
Array1.push_back(10);
std::cout << "Value 2 is inserted at index " << Array1.insert(1, 2) << std::endl;
However when I run the code, I always get this "Terminate called after throwing an instance of std::range_error: index out of bounds"
I know this shouldn't be happening because my beforeIndex = 1 which is smaller than size_ = 3.
You could answer that in seconds by stepping through the program in your debugger. If you don't know how to do that, find out before writing any more code.
But given the code shown, I am pretty sure it's because push_back always calls insert with size_ as the first argument (line 2), and then insert always throws when the first argument equals size_ (line 11)