Search code examples
vectorbinary-search

Handling vector elements dynamically, with good performance


I need to handle various (varied at runtime) amount of pointers in a vector. That is, I need sometimes to remove certain elements, i.e., as I understood, there will be some "empty slots" in the vector. 1./ What is the method (with good performance) to make "compact" the vector again (after "remove") 2./ I want to use binary search (for speed). I did not see a template, that returns the index of the element, rather than returning a boolean if an element was found, only hand-coded methods. 3./ Are there any risks if I use (for sorting) uint casting, and compacting the elements? (I am working with SystemC, that as far as I understand, uses one thread only.)


Solution

    1. You can use resize() to shrink the size after you remove the elements. But using erase() method will do the resizing for you.
    2. To search for a particular element, you need to iterate through the elements in vector. Alternatively, you can use std::map which offers find() method that you can quickly search for an element and get it's index.
    3. You are right, Accellera's SystemC implementation uses single thread. Using container methods would be safer instead of dealing with saw elements and pointers.