@LarryChen: Don't assume the answer will always be the same as this, though. On my system (Ubuntu Linux using g++ 4.2.3) the following code (Philip Nicoletti's code with some output added):
Gives the following output:Code:#include <vector> #include <iostream> using namespace std; int main() { vector<int> v; size_t saved_capacity = v.capacity(); int number_of_reallocations = 0; for (int i=0; i<1000; ++i) { v.push_back(i); size_t current_capacity = v.capacity(); if (current_capacity != saved_capacity) { ++number_of_reallocations; saved_capacity = current_capacity; cout << "Reallocation at I = " << i << "\tCapacity\t" << current_capacity << endl; } } cout << endl << "Total reallocations = " << number_of_reallocations << endl; return 0; }
I.e. there are 11 reallocations, and the capacity is doubled each time a reallocation is required.Code:Reallocation at I = 0 Capacity 1 Reallocation at I = 1 Capacity 2 Reallocation at I = 2 Capacity 4 Reallocation at I = 4 Capacity 8 Reallocation at I = 8 Capacity 16 Reallocation at I = 16 Capacity 32 Reallocation at I = 32 Capacity 64 Reallocation at I = 64 Capacity 128 Reallocation at I = 128 Capacity 256 Reallocation at I = 256 Capacity 512 Reallocation at I = 512 Capacity 1024 Total reallocations = 11
It would be interesting to see what strategy the VC 2010 implementation is using to take 18 reallocations.




Reply With Quote