gpt4 book ai didi

c++ - 数组末尾指向新分配的数组 C++

转载 作者:搜寻专家 更新时间:2023-10-31 01:37:25 24 4
gpt4 key购买 nike

我正在尝试使用 C++ 创建一个数组,其中包含指向我正在存储的对象的指针。但是当数组满了,我想扩充数组。

简单的选择是分配一个更大的新数组,然后将元素复制到它,这是非常低效的,我想到了另一种我想尝试的方法:

  1. 创建固定大小的数组X

  2. 满后,新建一个数组,并使第一个数组的末尾指向第一个元素的开始

  3. 根据需要重复

我可以使用什么方法来做到这一点?我想到了一种方法,但它看起来很 hacky:

将我所有的新数组声明为指向对象指针的指针,然后将填充的元素重新解释为对象指针。

注意:我知道我可以使用 Vector,但我被指示不要使用标准库


亲切的问候,

最佳答案

评论中已经有一些不错的答案。我只是想提供一种方法来完全您所描述的行为。

由于数组的元素也是指针,您可以像这样将 union 定义为数组的元素:

template<typename T>
union Cell
{
T* pElm;
Cell* pNext;//A fixed size array of Cells
}

然后在其上构建您的数组。例如:

template<typename T>
class SpecialArray
{
public:
//the next pointer is included
static const size_t ARRAY_LEN = 1000;// For example
using Pointer = T*;
using Segment = Cell<T>[ARRAY_LEN];

protected:
Segment* pFirst;
size_t mSize;

public:
SpecialArray()
:pFirst(nullptr),mSize(0){}
SpecialArray(SpecialArray&&){}
~SpecialArray(){}

Pointer& operator[](size_t index)
{
Segment* seg = pFirst;
size_t offest = 0;
//Search logic...

return seg[offest]->pElm;
}
const Pointer& operator[](size_t index) const;
};

关于c++ - 数组末尾指向新分配的数组 C++,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34150216/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com