とくにあぶなくないRiSKのブログ

危ないRiSKのブログだったかもしれない。本当はRiSKだけどググラビリティとか取得できるIDの都合でsscriskも使ったり。

capacity, reserve, std::vector

// P134 ex06-06.cpp
struct U{
 unsigned long id;
 U():id(){}
 U(unsigned long x):id(x){}
};
#include<iostream>
#include<vector>

const int N = 10000;
using std::cout;
using std::endl;
using std::vector;

template<typename Container>
void Test(Container& c){
 for(int i = 0; i != N; ++i){
  const Container::size_type cap = c.capacity();
  c.push_back(U(i));
  if(c.capacity() != cap)
   cout << "i: " << i << ", new capacity: " << c.capacity() << endl;
 }
}
int main(){
 cout << "Demonstrating STL vector capacity and reserve functions." << endl;

 vector<U> v1;
 cout << "Doing " << N << " insertions in v1,\n"
  "with no advance reservation.\n";
 Test(v1);

 vector<U> v2;
 v2.reserve(N);
 cout << "\nNow doing the same thing with v2,\n"
  "after starting with reserve(" << N << ").\n";
 Test(v2);
}

出力例:

Demonstrating STL vector capacity and reserve functions.
Doing 10000 insertions in v1,
with no advance reservation.
i: 0, new capacity: 1
i: 1, new capacity: 2
i: 2, new capacity: 3
i: 3, new capacity: 4
i: 4, new capacity: 6
i: 6, new capacity: 9
i: 9, new capacity: 13
i: 13, new capacity: 19
i: 19, new capacity: 28
i: 28, new capacity: 42
i: 42, new capacity: 63
i: 63, new capacity: 94
i: 94, new capacity: 141
i: 141, new capacity: 211
i: 211, new capacity: 316
i: 316, new capacity: 474
i: 474, new capacity: 711
i: 711, new capacity: 1066
i: 1066, new capacity: 1599
i: 1599, new capacity: 2398
i: 2398, new capacity: 3597
i: 3597, new capacity: 5395
i: 5395, new capacity: 8092
i: 8092, new capacity: 12138

Now doing the same thing with v2,
after starting with reserve(10000).