Follow me

Tuesday, 25 August 2020

abstract data type Array adt with classes | user define datatype | abstract datatype | c++ | cpp

abstract data type Array adt with classes

An Abstract Data Type (ADT) is an abstract concept defined by axioms that represent some data and operations on that data. ADTs are not defined in terms of concrete instances and do not specify the concrete data types, structures, or algorithms used in implementations. Instead, ADTs define data types only in terms of their operations, and the axioms to which those operations must adhere.


Implamentation:

#include <bits/stdc++.h>
using namespace std;

class Array
{
private:
    int total_size;
    int used_size;
    int *ptr;

public:
    Array()
    {

        this->total_size = 100;
        this->used_size = 1;
        this->ptr = new int[total_size];
        (this->ptr)[0] = 0;
    }
    Array(const int &used_size)
    {

        this->total_size = 100;
        this->used_size = used_size;
        this->ptr = new int[total_size];
    }
    Array(int total_size, int used_size)
    {

        this->total_size = total_size;
        this->used_size = used_size;
        this->ptr = new int[total_size];
    }
    ~Array() {}

    const int &at(const int &index) const
    {
        return (this->ptr)[index];
    }
    void show();
    int &operator[](int);
    void insert(const int &, const int &);
    void insert(const int &);

    const int &size() const { return this->used_size; };
    const int &capacity() const { return this->total_size; };
};

void Array::insert(const int &index, const int &element)
{
    (this->ptr)[index] = element;
}

void Array::insert(const int &element)
{
    (this->ptr)[this->used_size] = element;
    used_size++;
}

void Array::show()
{
    for (int i = 0; i < this->used_size; ++i)
        cout << (this->ptr)[i] << "\n";
}

int &Array::operator[](int index)
{
    if (index >= used_size)
    {
        cout << "Array index out of bound, exiting";
        exit(0);
    }
    return (this->ptr)[index];
}

int main()
{
    int size;
    cout << "Enter the size of Array: ";
    cin >> size;
    Array a(size);
    int temp;
    cout << "\nEnter " << size << " element" << endl;
    for (int i = 0; i < size; ++i)
    {
        cout << "element no." << i + 1 << ": ";
        cin >> temp;
        a[i] = temp;
    }
    cout << "\nAll element are: " << endl;
    a.show();
    cout << "\nFirst element is: " << a.at(0) << endl;
    cout << "size of Array is: " << a.size() << endl;
    cout << "capacity of Array is: " << a.capacity() << endl;

    return 0;
}




    Output:



No comments: