Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Are there functions to request capacity for std::set?

Tags:

c++

set

For std::vector, we can use vector::reserve(n) to request that the vector capacity be at least enough to contain n elements. So what about std::set? Do we have similar function to reserve its capability? I ask this question is because sometimes it is a request to allocate enough capability for std::set variable when it is used as a reference argument of a function, which comes from another dynamic library (Multi-threaded Debug (/MTd) is used).

EDIT

One possible solution might be using get_allocator function:

std::set<float> abc;
    float *p;
    p = abc.get_allocator().allocate(100);
    for(int i=0; i<100; i++)
        abc.insert(abc.end(),i);

    std::set<float>::iterator it = abc.begin();
    std::set<float>::iterator itEnd = abc.end();
    while(it != itEnd)
    {
        std::cout<<(*it)<<std::endl;
        it++;
    }

     abc.get_allocator().deallocate(p,100);
like image 709
feelfree Avatar asked Feb 21 '14 09:02

feelfree


1 Answers

With a std::vector, it's important to provide functionality to reserve space, as it is guaranteed in the C++ standard that all elements in a vector be contiguous in memory. This means that if you try to push_back more items than are currently reserved, there is a need to allocate more memory, potentially in a different place, and potentially having to move existing items (I think this is implementation based). This all takes time, so instead you can reserve (or pre-allocate) the space you think you'll need.

Conversely, a container such as a std::set is generally implemented as a tree. The main difference here is that elements are often allocated dynamically as they are added. There is no requirement for items to be contiguous in memory, and so there is no need to "reserve" any space for said items - depending on the implementation, they can simply be allocated as they're needed, anywhere in available memory.

Not sure if that's the answer you were looking for.

like image 76
icabod Avatar answered Sep 29 '22 04:09

icabod