如何在C++中处理灵活的数组

Lap*_*pys 0 c++ memory-management flexible-array-member

上下文

所以我一直在玩C/C++中的数组,试图创建可以动态添加和删除元素的数组.

当然,我认为C语言中的灵活数组成员特征是合适的方式.所以我开始尝试,因为下面的代码显示:

#include <cstdio> // printing stuff
#include <stdlib.h> // memory allocation stuff

// The array type
template <typename structType>
struct Array {
    private:
        // The structure containing the F.A.M.
        struct ArrayStructure { size_t length = 0; structType array[]; }
            *arrayStructurePointer, arrayStructure;
        constexpr inline static void add() {}

    public:
        // Constructor
        template <typename... types, typename = structType>
        explicit Array(types... elements) {
            this -> arrayStructurePointer =
                (ArrayStructure*) malloc(sizeof(structType));
            this -> arrayStructurePointer = &(this -> arrayStructure);
            this -> add(elements...);
        }

        // Destructor
        ~Array() {
            free(this -> arrayStructurePointer);
            free(this -> arrayStructure.array);
        }

        // Add stuff to the array
        inline void add(structType element) {
            this -> arrayStructurePointer =
                (ArrayStructure*) realloc(this -> arrayStructurePointer, sizeof(this -> arrayStructure));
            this -> arrayStructurePointer = &(this -> arrayStructure);
            this -> arrayStructure.array[this -> arrayStructure.length] = element;
            this -> arrayStructure.length += 1;
        }
        template <typename... types, typename = structType>
        inline void add(structType element, types... elements) {
            this -> add(element);
            this -> add(elements...);
        }

        // Query an element in the array
        constexpr inline structType operator [](size_t index) { return *(this -> arrayStructure.array + index); }
};

int main(int argc, char* argv[]) {
    Array<int> array(1, 0, 1);

    printf("Array [0]: %i\n", array[0]);
    printf("Array [1]: %i\n", array[1]);
    printf("Array [2]: %i\n", array[2]);

    return 0;
}
Run Code Online (Sandbox Code Playgroud)

这一点的意义在于我(可能)了解vector工作方式和与之相关的挑战.


问题

我只是为数组添加元素,但即便如此,当我编译并运行代码时,程序在退出之前结束时会有这么大的延迟(我认为这是因为内存泄漏).


所以,问题是:我想断言我正在创建动态数组,通过询问如何构建动态数组来推送和弹出请求.

如何正确构建动态数组?要么

我如何建立自己的 vector 结构?要么

是否有任何好的资源/ PDF可以教授如何制作动态数组(或者)? vector

Yak*_*ont 6

只需std::vector用于可变长度数组.它比999/1000的手卷解决方案更好,更可靠地解决了这个问题.

  • 999/1000?你确定它那么低吗? (5认同)
  • @SergeyA我从来没有说过它具有挑战性,我只是说它是一些代码.它可能是最好的容器之一,因为它引入了所有库使用的许多概念. (3认同)
  • @Lapys你可以看到它[这里](https://codereview.stackexchange.com/questions/60484/stl-vector-implementation).还有一些[这里](https://codereview.stackexchange.com/questions/138389/my-own-stdvector).我也相信Bjarne Stroustrup的一本书也详细介绍了如何制作矢量. (2认同)