0
#include <vector>
#include <iostream>
using namespace std;

int main()
{
    vector<int> v;
    auto vsize = v.capacity();
    for (int tmp = 0; tmp < 1000;tmp++)
    {
        v.push_back(tmp);
        if(vsize!=v.capacity())
        {
            vsize = v.capacity();
            cout << "capacity changed : " << vsize << endl;
        }
    }
    return 0;
}

compiled by MSVC

compiled by GCC

vector's capacity should be previous double, why MSVC not work in this?

  • 3
    "vector's capacity should be previous double" you should stop to deduce requirements from behavior, but rely on documentation instead – Slava Jan 31 '18 at 20:06
  • 1
    There is a smurf-load of research on just how much capacity should increase on a resize, and no one agrees on exactly how much. I recall that the general consensus was somewhere between 1.5 and 2 is best for most cases. Looks like MSVC is putting a bit more thought into it, but how much that helps needs to be profiled on a case-by-case basis. – user4581301 Jan 31 '18 at 20:25
  • 2
    Two related questions popped up yesterday that may also be of interest to you: [Why are C++ STL vectors 1000x slower when doing many reserves?](https://stackoverflow.com/questions/48535727/why-are-c-stl-vectors-1000x-slower-when-doing-many-reserves) and [Why does std::vector reserve not “double” its capacity, while resize does?](https://stackoverflow.com/questions/48537812/why-does-stdvector-reserve-not-double-its-capacity-while-resize-does) – user4581301 Jan 31 '18 at 20:28

3 Answers3

6

vector's capacity should be previous double, why MSVC not work in this?

Where did you get that from?

That's implementation specific behavior. There's nothing said in the standard how capacity() should change after calling push_back(), besides it must guarantee the std::vector has enough (not double than before) space allocated.

1

vector's capacity should be previous double

That is wrong. The only requirement is that vector::push_back performs amortized O(1) copies. That can be achieved by multiplying the capacity by a constant factor every time a reallocation is required - but that constant does not have to be 2 (it does have to be greater than 1). GCC uses 2, MSVC uses 3/2. (The advantage of the latter is that it uses less space, at a cost of more copies)

0

"vector's capacity should be previous double". No it should not. How and by how much a std::vector increases its capacity when it grows is implementation defined.

This means that every implementation is free to do its own thing. It can double the size, increase it by 2, increase it 10-fold or whatever. From your point, as a user of the container, you cannot know and you are not supposed to care.

Jesper Juhl
  • 30,449
  • 3
  • 47
  • 70