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 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53
|
#include <iostream>
template <class T>
T* insertValue (T* originalArray, int positionToInsertAt, T ValueToInsert, int sizeOfOriginalArray)
{
// Create the new array - user must be told to delete it at some point
T* newArray = new T[sizeOfOriginalArray + 1];
for (T i=0; i<=sizeOfOriginalArray; ++i)
{
if (i < positionToInsertAt)
{
newArray[i] = originalArray[i];
}
if (i == positionToInsertAt)
{
newArray[i] = ValueToInsert;
}
if (i > positionToInsertAt)
{
newArray[i] = originalArray[i-1];
}
}
return newArray;
}
int main()
{
int x[5]={0, 1, 2, 3, 4};
for (int y=0;y<5;y++)
std::cout << x[y] << " ";
std::cout << std::endl;
int* z = insertValue(x,0,7,5);
for (int y=0;y<6;y++)
std::cout << z[y] << " ";
std::cout << std::endl;
delete[] z;
char a[4] = { 'a', 'b', 'c', 'd'};
for (int y=0;y<5;y++)
std::cout << a[y] << " ";
std::cout << std::endl;
char* b = insertValue(a,2,'z',5);
for (int y=0;y<6;y++)
std::cout << b[y] << " ";
delete[] b;
return 0;
}
|