Нужна ли функция isFull () для класса контейнера массива Dynami c? - PullRequest
0 голосов
/ 16 марта 2020

У меня есть небольшая проблема, оборачивая это вокруг моей головы; Я использовал отладчик в VS для go через мой код. Я понял, что когда я вызываю функцию insertBack() в main(), элементы не вставляются, так как условие if (!isFull) не выполняется - возвращая false, в результате чего вставка не происходит. Я попытался удалить условие и получил несколько ошибок относительно моего кода, пытаясь вставить число в недопустимую часть массива. Проходя через это, я начал спрашивать себя, требуется ли функция isFull(), так как размер динамического c можно изменить; но как это может быть полным, если это так? Я немного изучил векторы cpprefrence и не нашел isFull() функцию-члена.

#include <iostream>

template<typename T>
class container
{
    template <typename T2>
    friend std::ostream& operator<<(std::ostream& out, const container<T2> &cobj);
    // Postcondition: contents of the container object cobj is displayed
public:
    container();
    // Postcondition: an empty container object is created with data members arr set to NULL, n set to -1 and Capacity set to 0
    ~container();
    // Destructor; required as one of the Big-3 (or Big(5) because of the presence of a pointer data member. Default version results in 
    //    memory leak!
    // Postcondition: dynamic memory pointed to by arr has been release back to the “heap” and arr set to NULL or nullptr
    //                 In order to see the action, message "destructor called and dynamic memory released!" is displayed
    bool isEmpty() const;
    // Postcondition: returns true is nothing is stored; returns false otherwise
    bool isFull() const;
    // Postcondition: returns true if arr array is filled to capacity; returns false otherwise
    int size() const;
    // Postcondition: returns the size or the number of elements (values) currently stored in the container
    int capacity() const;
    // Postcondition: returns the current storage capacity of the container
    bool insertBack(const T& val);
    // Postcondition: if container is not full, newVal is inserted at the end of the array; 
    //                otherwise, double the current capacity followed by the insertion
    bool deleteBack();
    //  Precondition: The array must not be empty
    // Postcondition: the last element stored in the array is removed! size of the container is decremented by 1, capacity unchanged
    void clear();
    // Postcondition: all elements in arr of calling container object are cleared and the dynamic memory is released back to “heap” 
private:
    void allocate(T* &temp);
    // Postcondition: if Capacity = 0, allocate a single location; otherwise the current capacity is doubled
    T *arr;
    int Capacity;   // Note: Capital 'C' as capacity is used as a function name
    int n;          // size or actual # of values currently stored in the container; n <= SIZE
};

template<typename T2>
std::ostream& operator<<(std::ostream& out, const container<T2> &cobj)
{
    std::cout << "Currently it contains " << cobj.size() << " value(s)" << std::endl
        << "Container storage capacity = " << cobj.capacity() << std::endl
        << "The contents of the container:" << std::endl;

    if (cobj.isEmpty())
    {
        std::cout << "*** Container is currently empty!" << std::endl;
    }
    else
    {
        for (int i=0; i<cobj.size(); ++i)
        {
            std::cout << cobj.arr[i];
        }
    }

    return out;
}

template<typename T>
container<T>::container()
{
    arr = nullptr;
    Capacity = 0;
    n = 0;
}

template<typename T>
container<T>::~container()
{
    delete arr;
    arr = nullptr;
    std::cout << "Destructor called! (this line is normally not displayed)" << std::endl;
}

template<typename T>
bool container<T>::isEmpty() const
{
    return n==0;
}

template<typename T>
bool container<T>::isFull() const
{
    return n==Capacity;
}

template<typename T>
int container<T>::capacity() const
{
    return Capacity;
}

template<typename T>
int container<T>::size() const
{
    return n;
}

template<typename T>
bool container<T>::insertBack(const T& val)
{
    if (!isFull())
    {
        n++;
        arr[n-1] = val;
        return true;
    }
    else
    {
        return false;
    }
}

template<typename T>
bool container<T>::deleteBack()
{
    if (!isEmpty())
    {
        n--;
        return true;
    }
    else
    {
        return false;
    }
}

template<typename T>
void container<T>::clear()
{
    if (!isEmpty())
    {
        n = 0;
        return true;
    }
    else
    {
        return false;
    }
}

template<typename T>
void container<T>::allocate(T* &temp)
{
    if (Capacity==0)
    {
        temp = new T;
    }
    else
    {
        return Capacity*2;
    }
}

int main()
{
    container<int> a1;
    std::cout << a1 << std::endl; 
    std::cout << "Currently, the container object contains 0 element(s) or 0 value(s)" << std::endl;

    std::cout << "\nWe now insert 3 values at the back of the array, one at a time:" << std::endl;

    const int num = 3;
    for (int i=0, c=0; i<=num; ++i, c+=10)
    {
        a1.insertBack(c);
    }

    std::cout << a1;
}

Ответы [ 2 ]

1 голос
/ 16 марта 2020

Я думаю, что метод isFull не имеет смысла, так как ваш динамический контейнер c не ограничен в емкости. Вместо этого вы можете использовать методы size и capacity для отслеживания состояния контейнера.

0 голосов
/ 16 марта 2020

Если вы хотите реализовать вектор и хотите проверить, меньше ли размер или равен емкости, а затем решить, следует ли изменить его размер, вы можете обернуть size > = capacity в качестве закрытой функции isFull (). Но я думаю, что не имеет смысла устанавливать его публично c.

...