0

For some reason, I have a vector of pointer of struct, I would like to assign new space to every block of the vector. But I don't want to do it in a loop for every block as it may slow the whole process. Is there a faster way to do it? Could anyone provide me a solution with code?

This is what I current doing("pool" is the struct name):

vector<pool*> poolPointer(vectorSize);
for(int i = 0; i<poolPointer.size() ;i++){
     poolPointer.at(i) = new pool;}

I think it is very slow thus I would like to search for a faster way to allocate space and return point of struct to each individual block in the vector.

Carl
  • 105
  • 3
  • 12
  • I did not underunderstood it completely.. Can you elaborate..? – PRIME Dec 08 '15 at 12:25
  • You can use `std::vector::reserve()` to avoid excessive reallocation if you know in advance how big your vector will need to be. – Tristan Brindle Dec 08 '15 at 12:27
  • @OP, what do you mean by 'every block of the vector' ? Please rephrase the question to make it more clear. – Arunmu Dec 08 '15 at 12:28
  • We don't have much detail here. Please show us some code. – Logicrat Dec 08 '15 at 12:30
  • 1
    Where is the ownership of those structs (which object or function is responsible for freeing the memory allocated for those structs)? I think what you were trying to ask is how to efficiently allocate structs to be pointed to by all the pointers of some initial size of the vector. If ownership were somehow not a problem then allocating a `T[]` of them and pointing to each of those would be faster than individual allocations. But likely that would conflict with any sane design you might have for ownership. – JSF Dec 08 '15 at 13:17
  • I added more information – Carl Dec 08 '15 at 13:49
  • @TristanBrindle The problem is I need to assign data to my vector of struct, `std::vector::reserve()` does not create space but just capacity. Thus assignment can't be carried out. – Carl Dec 08 '15 at 13:52

1 Answers1

0

I has nothing to do with vector. What you are looking for is custom memory allocation, and in place operator new in particular. So you can allocate a single chunk of memory for all your pool instances and then create instances in this memory chunk.

EDIT:

As @JSF commented, you can allocate many instances all together as an array of "values", not pointers. You can then use vector of pointers if you wish, or you can use vector of values and don't bother with pointers at all. I'd start with vector of values and only if profiling showed that frequent removal from a vector is a bottleneck I'd think about vector of pointers as an optimisation.

Community
  • 1
  • 1
Andriy Tylychko
  • 15,967
  • 6
  • 64
  • 112