A container finding which can be resized smaller

Hi everyone.
I want to find a container, which at first be allocated very large. (with Intention to be large enough to contain my things)
Then I fill it but don't know how many elements be coming (like SQL query)
At last I resize it to small.

I do not repeat this workaround again, but want to have a good performance.
So only once allocate large and only once resize to small necessary size.
Examples I tried.
1
2
3
4
5
6
7
    constexpr size_t SIZE = 1 << 16;
    vector<int> v; 
    v.reserve(SIZE); 
    auto ptr = &v[0];
    for (size_t i = 0; i < 5; ++i) { *ptr = i; ptr++; }
    // 5 is only a example, this number is unknown
    v.resize(5);  // all previous data lost 


1
2
3
4
5
6
7
    constexpr size_t SIZE = 1 << 16;
    vector<int> v; 
    v.resize(SIZE); 
    auto ptr = &v[0];
    for (size_t i = 0; i < 5; ++i) { *ptr = i; ptr++; }
    // 5 is only a example, this number is unknown
    v.resize(5);  // worked, but double resize is super slow 
http://www.cplusplus.com/reference/vector/vector/shrink_to_fit/
v.reserve( a lot )
while more data
  v.push_back( item )
v.shrink_to_fit()
careless overuse of this will make performance sluggish, but occasional use of it can be sharp. Just be aware that shrink to fit can be a rather expensive operation. Its the opposite problem of misuse of push back (without a reserve), but similar results.
Last edited on
Topic archived. No new replies allowed.