How to insert and delete an element of a 1-D array.
for ex:
suppose the array is: 1 3 4 2 5
we want to insert 7 between 3 and 4 so that the new array is: 1 3 7 4 2 5
views:
106answers:
4Arrays aren't very easy to deal with when you want to insert or remove an element. You would have to manually copy the data forward by 1 position to insert 1 element to make a new slot available.
To do this with less work to you, you can use an STL vector:
#include <vector>
//...
std::vector<int> v;
v.push_back(1);
v.push_back(3);
v.push_back(4);
v.push_back(2);
v.push_back(5);
v.insert(v.begin() + 2, 7);
v.erase(v.begin());//Removing the first element just for fun
Even with a vector though you are still copying data (just transparently to you). So to do this most efficiently you would use an std::list.
#include <list>
//...
std::list<int> v;
v.push_back(1);
v.push_back(3);
v.push_back(4);
v.push_back(2);
v.push_back(5);
v.insert(++(++v.begin()), 7);
v.erase(v.begin());//Removing the first element just for fun
If you want to insert elements then using a list would be more appropriate -- arrays are sequential memory blocks so if you want to insert something you have to do work:
increase the size of the array
for each element past the spot - move one element further back
write new element at the target position
You can't do this with an array in C++ -- you'd have to reallocate the array and move the elements. Use a std::vector instead, and the insert method:
std::vector<int> v;
v.push_back( 1 );
v.push_back( 3 );
v.push_back( 4 );
v.push_back( 2 );
v.push_back( 5 );
// begin() yields an iterator to the first element; since it's a random-access
// iterator we can offset to insert at index 2.
v.insert( v.begin() + 2, 7 );
erase can be used in a similar fashion to remove items.