#include<iostream>
using namespace std;
template<typename T>
class List
{
public:
T *values;
int capacity;
int counter;
public:
List()
{
values = NULL;
capacity = 0;
counter = 0;
}
List(int cap)
{
capacity = cap;
values = new T[cap];
counter = 0;
}
bool insert(T item)
{
if (isFull() == false)
{
values[counter] = item;
counter++;
return true;
}
return false;
}
bool insertAt(T item, int index)
{
if (isFull() == false && index < counter)
{
capacity++;
for (int i = capacity; i > index; i--)
values[i] = values[i - 1];
values[index] = item;
return true;
}
return false;
}
bool isFull()
{
if (counter == capacity)
{
return true;
}
return false;
}
void print()
{
for (int i = 0; i < capacity; i++)
{
cout << values[i] << " ";
}
}
};
int main()
{
List<int> obj1(5);
obj1.insert(1); //0
obj1.insert(2); //1
obj1.insert(3); //2
obj1.insert(4); //3
obj1.insertAt(3, 1);
obj1.values[1];
obj1.print();
}
Kindly look into this program I have to insert an element at given position. But when I run this program I am getting garbage at the end element of an array. Kindly check and let me know where is the problem? Please check the insertAt function I think this function has some logical error. I have added the main function when I call print function it give garbage at the last index