user9109807
user9109807

Reputation: 3

vector behavior differ between MSVC and GCC

#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?

Upvotes: 0

Views: 572

Answers (3)

user9212993
user9212993

Reputation:

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.

Upvotes: 6

Jesper Juhl
Jesper Juhl

Reputation: 31468

"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.

Upvotes: 0

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)

Upvotes: 1

Related Questions