连续的新对象的数组 [英] Array of contiguous new objects
问题描述
我目前填补像这样元素的矢量数组:
的std ::矢量< T *> elemArray; 用于(为size_t我= 0; I< elemArray.size(); ++ I)
{
elemArray =新T();
}
在code显然被简化。现在问另一个问题(无关这个问题,但相关的程序)后,我意识到我需要一个数组 new'd
对象(不能在栈上,会溢出,元素过多),但是是连续的。也就是说,如果我要得到一个元素,没有数组索引,我应该可以做找到数组索引 returnedElement - elemArray [0]
来获得指数阵列中的元素的。
我希望我已经说明了问题,如果没有,请让我知道哪些部分,我将试图澄清。
编辑:我不知道为什么最高投票的回答是不被看到。我已经尝试了很多次。如果我试着分配这样的载体超过10万(约)的元素,它总是给我一个内存错误。其次,我需要指针,因为从我的例子清楚。突然改变它不是指针将需要大量的code重新编写的(虽然我很愿意这样做,但它仍然是一个几百万要素分配这样的载体不工作没有解决问题
块引用>解决方案A
的std ::矢量<>
存储它在堆中分配的数组元素,它赢得 T商店堆栈上的元素。所以,你不会得到任何堆栈溢出,即使你做的简单的方法:的std ::矢量< T> elemArray;
用于(为size_t我= 0; I<的elemcount ++我){
elemArray.push_back(T(I));
}
&放大器; elemArray [0]
将是一个指向T
对象(连续)阵列<。 / p>I am currently filling an vector array of elements like so:
std::vector<T*> elemArray; for (size_t i = 0; i < elemArray.size(); ++i) { elemArray = new T(); }
The code has obviously been simplified. Now after asking another question (unrelated to this problem but related to the program) I realized I need an array that has
new'd
objects (can't be on the stack, will overflow, too many elements) but are contiguous. That is, if I were to receive an element, without the array index, I should be able to find the array index by doingreturnedElement - elemArray[0]
to get the index of the element in the array.I hope I have explained the problem, if not, please let me know which parts and I will attempt to clarify.
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<>
stores its elements in a heap allocated array, it won't store the elements on the stack. So you won't get any stack overflow even if you do it the simple way:std::vector<T> elemArray; for (size_t i = 0; i < elemCount; ++i) { elemArray.push_back(T(i)); }
&elemArray[0]
will be a pointer to a (continuous) array ofT
objects.这篇关于连续的新对象的数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!