c++ - 在类中创建动态数组 (C++)

标签 c++ class arraylist

我想用数组实现一个类。如果数组的大小被破坏,我会调用 resize() 函数。但是我似乎无法将动态数组编码为数据成员。有人可以指导我如何解决这个问题吗?

这是我到目前为止得到的:

class ArrayList
{
        public:
        ArrayList()
        {
                array[ARR_SIZE] = {0};
                space = 0;
                size = ARR_SIZE;
        }
        void insert(int place, int value)
        {
                if (place >= size)
                        cout << "Sorry, that index is not accessible" << endl;
                else
                {
                        array[place] = value;
                        space++;

                if(space == size)
                        allocate();
                }
        }
        void remove(int place)
        {
                if(place >= size)
                        cout << "Sorry, that index is not accessible" << endl;
                else
                {
                        array[place] = NULL;
                        space--;
                }

        }
        void allocate()
        {
                int* array = new int[size*2];
                size = size*2;
        }
        int usedSize()
        {
                return space;
        }
        int totalSize()
        {
                return size;
        }
        private:
        int array[ARR_SIZE];
        int space;
        int size;
};

最佳答案

使用std::vector . C++ 在类或其他方面不支持可变长度或动态大小的数组。

关于c++ - 在类中创建动态数组 (C++),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25298266/

相关文章:

c++ - 如何将最终迭代添加到 while 循环?

c++ - 什么是 undefined reference /未解析的外部符号错误以及如何修复它?

c++ - 层次结构中类的编译器错误

java - 添加重复字符串的数量

java - 在 Swing 中获取选定的单选按钮列表

C++ openGL拾取问题

c++ - 范围到值组的高效映射

c++ - 在成员函数中访问参数的类成员

Java变量/对象?双向链表逻辑

java - Java 中多维数组的 ClassCastException