Multi-Cab
Multi-Cab

Reputation: 11

C++ custom array container dynamic size

For a school assignment I want to build a custom array container as I'm not allowed to use containers provided by std, or any library available, while self made is allowed.

So far everything I have is working but I want to double my array size as soon as I reach the limit. how can i do this, all i can find is using vector (which i'm not allowed).

#ifndef UTILS_ARRAY_HEADER_INCLUDED
#define UTILS_ARRAY_HEADER_INCLUDED

#include <array>

namespace utils
{
    template <class T>
    struct Array
    {

    private:
        int count = 0;
        int size = 1;

        std::array<T, 1> myArray;
        void doubleSize();
    public:
        T* begin();
        T* end();
        T& operator[] (int);
        void addItem(T const);
    };

    template <class T>
    T* Array<T>::begin()
    {
        return &myArray[0];
    }

    template <class T>
    T* Array<T>::end()
    {
        if (&myArray[count])
            return &myArray[count];
        return &myArray[0];
    }

    template <class T>
    T& Array<T>::operator[] (int key)
    {
        return myArray[key];
    }

    template <class T>
    void Array<T>::addItem(T const item)
    {
        if (count >= 0 && count < size)
        {
            myArray[count] = item;
            count++;
        }
        else {
            doubleSize();
        }

        return;
    }

    template <class T>
    void Array<T>::doubleSize()
    {
        // ?
        /*size = size * 2; 
        const int newsize = 2;
        std::array<T, newsize> newArray; // not working.
        std::copy(std::begin(myArray), std::end(myArray), std::begin(newArray));
        myArray = newArray;*/
    }
}

#endif

Upvotes: 0

Views: 956

Answers (2)

Krzysztof Skowronek
Krzysztof Skowronek

Reputation: 2936

You need properties:

  • current capacity: int
  • current size (max used index): int
  • pointer to your data: T *

In AddItem check if current_size < current_capacity. If yes, create new_data with size of currernt_capacity * 2, copy each item, delete old data and replace pointer.

Remember to do delete data; in destructor. I won't give you more code, it's your homework.

Checkout valgrind to check if your code does not leak memory.

Upvotes: 1

MSalters
MSalters

Reputation: 179799

I suspect that std::array<T, 1> is not allowed either. But that's not a real problem: you can't use array anyway since it has a fixed size.

You'll need to store a T* begin, a size_t current_size and a size_t size_in_use.

Upvotes: 0

Related Questions