语境
所以我一直在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
的工作方式以及与之相关的挑战。问题
我只是想向数组添加元素,即使这样,
当我编译并运行代码时,程序在退出之前结束时会有很大的延迟(我认为这是由于内存泄漏)。
题
所以,问题是:我想断言我正在遵循正确的路径来创建动态数组,该数组通过询问如何构建动态数组来按需推送和弹出。
如何正确构建动态数组?要么
如何建立自己的
vector
结构?要么是否有任何好的资源/ PDF可以教如何制作动态数组(或
vector
)? 最佳答案
只需对可变长度数组使用std::vector
。与您的手动解决方案在999/1000情况下相比,它可以更好,更可靠地解决此问题。
关于c++ - 如何在C++中处理灵活的数组,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/54874850/