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

问题描述 投票:0回答:1

Context

所以我一直在玩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;
}

关键在于我(可能)了解vector的工作方式以及与之相关的挑战。


Problem

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


Question

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

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

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

有没有什么好的资源/ PDF可以教授如何制作动态数组(或vector)?

c++ memory-management flexible-array-member
1个回答
6
投票

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

© www.soinside.com 2019 - 2024. All rights reserved.