读书笔记《effective stl》item14: 使用reserve来避免不必要的重新分配
在容器刚被构造出来之后就使用reserve,可以减少不必要的重新分配的时间。
#include <iostream>
#include <vector>
#include "time.h"
using namespace std;
typedef vector<int> VI;
template<class T>
T push_int_containers(int large, int small, T c)
{
for (int i = large; i>small ; i--)
{
c.push_back(i);
}
return c;
}
template<class T>
void print_containers(string name,T c)
{
cout << "\n" << name <<" : ";
for (auto i = c.begin(); i != c.end(); ++i)
{
cout << *i << " ";
}
cout << "\n";
}
int main()
{
VI v1,v2;
auto b1 = clock();
v1.reserve(10000);
for (int i = 10000; i>1 ; i--)
{
v1.push_back(i);
}
auto e1 = clock();
cout << "v1 spends " << e1 - b1 << "\n";
auto b2 = clock();
for (int i = 10000; i>1 ; i--)
{
v2.push_back(i);
}
auto e2 = clock();
cout << "v2 spends " << e2 - b2 << "\n";
return 0;
}
输出结果为:
v1 spends 278
v2 spends 337