Insert an element

Hi all,

Here's the functions I have

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
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.

Any suggestion on how to fix this?

Thank you.
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)
@Cubbi

Thank you for your answer. I'm still learning how to debug program. So please be patient with me :)

I was suspecting the reason was like what you said. I'm still trying to find a way to get around this. I was thinking to do something like this
1
2
if (beforeIndex >= size_)
   then set beforeIndex = size_


However, it's required that I have to throw something if beforeIndex >= size_ is the case.
Line 2: insert( size_, value );
Lines 11&12:
1
2
    if (beforeIndex >= size_)
        throw std::range_error("index of bounds"); 


So naturally if you call insert(size_, value), you're it's going to throw the exception.

Other comments:
- either insert() or push_back() should grow the array if necessary.
- line 14: What if beforeIndex==0?

I think lines 14-20 should be:
1
2
3
4
5
for (size_t dst = size_; dst != beforeIndex; --dst) {
    array_[dst] = array_[dst-1];
};
array_[beforeIndex] = value;
++size_;

Topic archived. No new replies allowed.