Search
 
SCRIPT & CODE EXAMPLE
 

CPP

how to use custom array in c++

template<typename T>
class array
{
public:
    typedef T* iterator;
    typedef const T* const_iterator;
private:
    iterator head;
    unsigned long elems;
public:
    array()
        : head(nullptr)
        , elems(0) {}
    array(const unsigned long &size)
        : head(size > 0 ? new T[size] : nullptr)
        , elems(size) {}
    array(const T[]);
    array(const array&);
    ~array() { delete[] head; }

    iterator begin() const { return head; }
    iterator end() const { return head != nullptr ? &head[elems] : nullptr; }
    unsigned long size() const { return elems; }

    array& operator=(const array&);
    T& operator()(const unsigned long&);
};

template<typename T>
array<T>::array(const T rhs[])
{
    unsigned long size = sizeof(rhs) / sizeof(T);
    head = new T[size];
    iterator pointer = begin();
    for (const_iterator i = &rhs[0]; i != &rhs[0] + size; i++)
        *pointer++ = *i;
}

template<typename T>
array<T>::array(const array<T> &rhs)
{
    head = new T[rhs.size()];
    iterator pointer = begin();
    for (const_iterator i = rhs.begin(); i != rhs.end(); i++)
        *pointer++ = *i;
}

template<typename T>
array<T>& array<T>::operator=(const array<T> &rhs)
{
    if (this != &rhs)
    {
        delete[] head;
        head = new T[rhs.size()];
        iterator pointer = begin();
        for (const_iterator i = rhs.begin(); i != rhs.end(); i++)
            *pointer++ = *i;
    }
    return *this;
}

template<typename T>
T& array<T>::operator()(const unsigned long &index)
{
    if (index < 1 || index > size())
    {
        // Add some error-handling here.
    }
    return head[index - 1];
}
Comment

PREVIOUS NEXT
Code Example
Cpp :: input n space separated integers in c++ 
Cpp :: c++ function as paramter 
Cpp :: cpp lambda function 
Cpp :: getline 
Cpp :: show stack c++ 
Cpp :: vector c++ 
Cpp :: binary search in c++ 
Cpp :: c++ finding gcd 
Cpp :: factorial in c++ using recursion 
Cpp :: count number of prime numbers in a given range in c 
Cpp :: c++ tuple 
Cpp :: how to use a non const function from a const function 
Cpp :: map count function c++ 
Cpp :: how to find even and odd numbers in c++ 
Cpp :: cpp linked list 
Cpp :: c++ data types 
Cpp :: Fisher–Yates shuffle Algorithm c++ 
Cpp :: c++ uint8_t header 
Cpp :: disallowcopy c++ 
Cpp :: heredar constructor c++ 
Cpp :: power in c++ 
Cpp :: how to fill vector from inputs c++ 
Cpp :: intersection between vector c++ 
Cpp :: c++98 check if character is integer 
Cpp :: backtrack 
Cpp :: string append at position c++ 
Cpp :: c++ program to find gcd of 3 numbers 
Cpp :: c++ pass function as argument 
Cpp :: not c++ 
Cpp :: activity selection problem 
ADD CONTENT
Topic
Content
Source link
Name
7+9 =