简体   繁体   English

C ++自定义数组容器的动态大小

[英]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. 对于学校作业,我想构建一个自定义数组容器,因为不允许使用std或任何可用库提供的容器,而允许自制。

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). 我该怎么做,我所能找到的就是使用vector(不允许这样做)。

#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

You need properties: 您需要属性:

  • current capacity: int 当前容量:整数
  • current size (max used index): int 当前大小(最大使用索引):int
  • pointer to your data: T * 指向您的数据的指针:T *

In AddItem check if current_size < current_capacity. 在AddItem中检查current_size <current_capacity。 If yes, create new_data with size of currernt_capacity * 2, copy each item, delete old data and replace pointer. 如果是,请创建新数据,其大小为currernt_capacity * 2,复制每个项目,删除旧数据并替换指针。

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. 检查valgrind以检查您的代码是否不会泄漏内存。

I suspect that std::array<T, 1> is not allowed either. 我怀疑std::array<T, 1>也不被允许。 But that's not a real problem: you can't use array anyway since it has a fixed size. 但这不是一个真正的问题:因为array具有固定的大小,所以无论如何都不能使用array

You'll need to store a T* begin , a size_t current_size and a size_t size_in_use . 您需要存储一个T* begin ,一个size_t current_size和一个size_t size_in_use

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM