gpt4 book ai didi

c++ - 连续的新对象数组

转载 作者:太空狗 更新时间:2023-10-29 23:42:08 24 4
gpt4 key购买 nike

我目前正在填充元素的 vector 数组,如下所示:

  std::vector<T*> elemArray;

for (size_t i = 0; i < elemArray.size(); ++i)
{
elemArray = new T();
}

代码明显简化了。现在又问了一个question (与这个问题无关但与程序有关)我意识到我需要一个数组,它有 new'd 对象(不能在堆栈上,会溢出,元素太多)但是是连续的。也就是说,如果我要接收一个没有数组索引的元素,我应该能够通过执行 returnedElement - elemArray[0] 来找到数组索引以获取数组中元素的索引.

我希望我已经解释了问题,如果没有,请告诉我哪些部分,我会尝试澄清。

EDIT: I am not sure why the highest voted answer is not being looked into. I have tried this many times. If I try allocating a vector like that with more than 100,000 (approximately) elements, it always gives me a memory error. Secondly, I require pointers, as is clear from my example. Changing it suddenly to not be pointers will require a large amount of code re-write (although I am willing to do that, but it still does not address the issue that allocating vectors like that with a few million elements does not work.

最佳答案

A std::vector<>将其元素存储在堆分配的数组中,它不会将元素存储在堆栈中。因此,即使您采用简单的方法,也不会出现任何堆栈溢出:

std::vector<T> elemArray;
for (size_t i = 0; i < elemCount; ++i) {
elemArray.push_back(T(i));
}

&elemArray[0]将是指向 T 的(连续)数组的指针对象。

关于c++ - 连续的新对象数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5747455/

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