首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >在将元素插入动态数组的后面时,是否有一种防止写入访问冲突的方法?

在将元素插入动态数组的后面时,是否有一种防止写入访问冲突的方法?
EN

Stack Overflow用户
提问于 2020-03-26 00:49:42
回答 1查看 86关注 0票数 0

我想使用insertBack()函数将元素添加到数组的后面;但是,当我尝试这样做时,我会得到一个错误:

引发的

未处理异常:写入访问冲突。此->arr为0x1110116。

我不知道我做错了什么;我的教授的帖子和前提条件让我很困惑。我也不知道如何分配,如果我的方式翻倍的能力是正确的。

容器类:

代码语言:javascript
复制
#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
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
};

函数定义/代码:

代码语言:javascript
复制
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 (size()>=Capacity)
    {
        Capacity = Capacity*2;
        n++;
        arr[n] = val;
        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;
}
EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2020-03-26 01:39:40

当您使用insertback()size() >= Capacity时,您的数组不会真正展开。您只需将名为Capacity的变量加倍,但是数组本身并没有增加一倍。

您可以尝试使用此代码将数组加倍如下:

代码语言:javascript
复制
T* old_array = arr; arr = new T[Capacity<<=1];  //double array
for(int i=0;i<n;++i) arr[i]=old_array[i]   //copy you can use memcpy instead for loop
delete [] old_array;    //free space

在代码中还发现了一些其他错误:

  1. 析构函数

您应该使用delete []arr而不是delete arr

delete释放将单个对象指针分配给new的内存。

delete []释放新分配的对象数组指针指向的内存。

并记住在使用delete.

  • insertback之前检查arr是否为nullptr。

n++;.

  • void container<T>::allocate(T* &temp)之前使用arr[n]=val;

allocate()的返回类型是void。因此,您不能return Capacity*2;.

提示:

我建议为Container设置默认容量。因此,当未指定容量时,请请求默认容量空间,而不是将容量设置为零。

票数 2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/60859497

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档