Need help inserting item into array

Hello, I'm pretty new to C++ and I'm trying to write a function that will insert a new item into an initialized array at a user specified index. I want the other values to move over to make room for the new item, i.e. insert 4 at 1st position into {1,2,3} should yield {1,4,2}, with the last element just disappearing. Here's what I have right now:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
void Insert(int array[], int SIZE)
{
int item; 
int insertPosition;
	
cout << "Enter a value to insert: ";
cin >> item; 
cout << "Enter the position to insert the value: ";
cin >> insertPosition; 

if(insertPosition <= SIZE)
{
    int i; 
    for(i = SIZE - 1; i > insertPosition; i--);
    {
       array[i] = array[i - 1];
       array[insertPosition] = item; 
    }
}
else
{
    cout << "Index out of bounds!" << endl;
    exit(0); 
}
}


The array size is declared as a global constant, which I just set to 5 for the time being. Currently, the new item overwrites the item in whatever position it's taking. So I ran it with inserting a 5 into position 3, and the output was
{0, 1, 2, 5, 4} when I want {0, 1, 2, 5, 3}. Any help would be greatly appreciated!
closed account (S6k9GNh0)
I'm confused... Take the following:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
#include <iostream>
 
template <typename T>
void insert(T* array, size_t offset, T data)
{
        array[offset] = data;
}
 
int main()
{
        int array[] = { 0, 1, 2, 3, 4, 5, 6 };
        insert<int>(array, 3, 7);
        //7 is the size of array
        for (int i = 0; i < 7; ++i)
        {
                std::cout << array[i];
        }
        std::cout << std::endl;
}


If you want bounds checking, the easiest way is to follow something similar to what the STL containers do and just track the size. If the offset is out of bounds, then throw an exception (or static assertion). You seem to have overcomplicated some things.
Last edited on
Topic archived. No new replies allowed.