Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Array of contiguous new objects

Tags:

c++

arrays

vector

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 doing returnedElement - 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.

like image 753
Samaursa Avatar asked Apr 20 '26 22:04

Samaursa


2 Answers

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 of T objects.

like image 157
sth Avatar answered Apr 23 '26 11:04

sth


If you need the elements to be contiguous, not the pointers, you can just do:

std::vector<T> elemArray(numberOfElements);

The elements themselves won't be on the stack, vector manages the dynamic allocation of memory and as in your example the elements will be value-initialized. (Strictly, copy-initialized from a value-initialized temporary but this should work out the same for objects that it is valid to store in a vector.)

I believe that your index calculation should be: &returnedElement - &elemArray[0] and this will work with a vector. Provided that returnedElement is actually stored in elemArray.

like image 35
CB Bailey Avatar answered Apr 23 '26 10:04

CB Bailey



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!