Search code examples
c++vectorstderaseobject-pooling

pop-push element from std::vector and reuse elements


i have a project in c++03 that have a problem with data structure: i use vector instead of list even if i have to continuously pop_front-push_back. but for now it is ok because i need to rewrite too many code for now.

my approach is tuo have a buffer of last frame_size point always updated. so each frame i have to pop front and push back. (mayebe there is a name for this approach?)

so i use this code:

Point apoint;  // allocate new point
apoint.x = xx;
apoint.y = yy;

int size = points.size()
if (size > frame_size) {
    this->points.erase( points.begin() );  // pop_front
}
this->points.push_back(apoint);

i have some ready-to-use code for an object pool and so i thought: it is not a great optimization but i can store the front in the pool and so i can gain the allocation time of apoint.

ok this is not so useful and probably it make no sense but i ask just to educational curiosity: how can i do that?

how can i store the memory of erased element of a vector for reusing it? does this question make sense? if not, why?

.. because erase does not return the erased vector, it return:

A random access iterator pointing to the new location of the element that followed the last element erased by the function call, which is the vector end if the operation erased the last element in the sequence.


Solution

  • i have some ready-to-use code for an object pool ... how can i do that?

    Using a vector, you can't. A vector stores its elements in a contiguous array, so they can't be allocated one at a time, only in blocks of arbitrary size. Therefore, you can't use an object pool as an allocator for std::vector.

    how can i store the memory of erased element of a vector for reusing it? does this question make sense? if not, why?

    The vector already does that. Your call to erase moves all the elements down into the space vacated by the first element, leaving an empty space at the end to push the new element into.

    As long as you use a vector, you can't avoid moving all the elements when you erase the first; if that is too inefficient, then use a deque (or possibly a list) instead.