Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Insert a new value to element of array and move the rest of elements

Tags:

c++

arrays

I am making a program that it will be able to add any numbers on an array and then it will be able to modify them (insert,delete).What I want to know is how to create a new value in an array without modifying anything.Just create the value and push all the rest to the next one.Example: insert 1 8 //insert is just the command,1 is the place where you want to create the new value and 8 is the value itself so list[1] = 8 but I want the rest values that already exist to go 1 forward(if they are in the place I want to create the new value or higher than it(talking about place in the list))

Full example: List:

5
6
7
8
9

Command: insert 3 10 New list:

5
6
7
10 //the one that changed,the rest from this point went 1 forward 
8
9
like image 301
user2699298 Avatar asked Dec 12 '25 09:12

user2699298


2 Answers

What you want is to use a std::vector<int> something like this:

std::vector<int> v = {5, 6, 7, 8, 9};
v.insert(v.begin() + 1, 8);   // v[1] now equals 8, everything after push up one
v.erase(v.begin() + 1);       // v is now as it was before above insert
v.insert(v.begin() + 3, 10);  // v[3] is now 10
like image 83
Paul Evans Avatar answered Dec 14 '25 00:12

Paul Evans


Let a be the array, position be the index in array where the value has to be inserted, and value be the value itself.

Then try:

int i;
for(i=CURRENT_SIZE_OF_ARRAY-1; i>=positon; --i)
{
   a[i+1] = a[i];
}
a[i]=value;

This way, you shift the array values from the end in order to make space for the new element, and then finally insert that element in the desired location.

like image 44
CinCout Avatar answered Dec 14 '25 01:12

CinCout