Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to insert element using template

I have some doubts about my insert method. it is compiling, but with no result )). I presume that it is containing some coding errors. Can you help me resolving this? Thanks in advance.

private:
 T*             elements;
 int            capacity;
 int            nbElements;
 
 template <class T>
void TableDynamic<T>::insert(const T& element, int index)
 {

 int *temp = new int[capacity] ;
 for(int i =0; i<nbElements; i++)
         {
 temp[i] = element;
          }
  delete[] elements;
 int *elem = new int[capacite];

}

>Solution :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

I have written some code for you. see if its works for you.

#include <iostream>
using namespace std;

// insert element using template
template <class T>
class TableDynamic
{
private:
    T *elements;
    int capacity;
    int nbElements;

public:
    TableDynamic(int capacity)
    {
        this->capacity = capacity;
        this->nbElements = 0;
        this->elements = new T[capacity];
    }

    void insert(const T &element, int index)
    {
        if (index < 0 || index > nbElements)
        {
            cout << "Index out of range" << endl;
            return;
        }
        if (nbElements == capacity)
        {
            cout << "Table is full" << endl;
            return;
        }
        for (int i = nbElements; i > index; i--)
        {
            elements[i] = elements[i - 1];
        }
        elements[index] = element;
        nbElements++;
    }

    void print()
    {
        for (int i = 0; i < nbElements; i++)
        {
            cout << elements[i] << " ";
        }
        cout << endl;
    }
};

int main()
{
    TableDynamic<int> table(10);
    table.insert(10, 0);
    table.insert(20, 1);
    table.insert(30, 2);
    // print the table
    table.print();

    return 0;
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading