How To insert an element into an array

Hello; I am pretty new to c++, and I'm having a problem with arrays. I want to know how to insert an element into an array; suppose I have an array x with numbers [1234567] how do I insert a new number into the array so that suppose I insert 9 just before 4, I have [12394567]. Please help me out on this cause I have read stuff on the internet about vectors, creating a new array and stuff like that. But I want to be able to manipulate the array to increase by one extra element and take something in whatever position I want, without affecting what was there before, looking forward to responses, thanks.

With a standard array you will need to shift everything to the right by one place in order to insert. You will need to make sure you have enough space allocated though

Something like

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
26
27
28
// Example program
#include <iostream>


int main()
{
    int array[10] = {1, 2, 3, 4, 5, 6, 7}; //space for 10 elements
    int size = 7;
    
    //insert 9 after 3.
    int insertPos = 3;
    
    for(int i = size++; i > insertPos; --i)
    {
        array[i] = array[i-1];
    }
    
    array[insertPos] = 9; //assign 9 to index 3 (4th element)

    for(int i = 0; i < size; ++i)
    {
        std::cout << array[i] << ' ';
    }
    
    std::cout << std::endl;
    
    return 0; 
}
yeah as said above, shift every element downwards & then add new element on that vacent place.
wow, it worked. Thanks
Topic archived. No new replies allowed.