background image

  注意上述这个向数组插入数据的过程是多么的繁琐。每次反复,循环都要检查缓存是

 

否达到上限。如果是,则程序调用用户定义的函数 reallocate(),该函数实现如下:

#include <algorithm

 

> // for std::copy

int reallocate(int* &p, int& size)
{
 size*=2; // double the array''s size with each reallocation
 int * temp = new int[size];
 std::copy(p, p+(size/2), temp);
 delete [] p; // release original, smaller buffer
 p=temp; // reassign p to the newly allocated buffer
}  

  reallocate() 

 

使用 STL std::copy() 

——

算法对缓存进行合理的扩充

每次扩充都放大一倍。

这种方法可以避免预先分配过多的内存,从量上减少需要重新分配的内存。这个技术需要
得到充分的测试和调试,当初学者实现时尤其如此。此外,reallocate() 并不通用,它只能
处理整型数组的情形。对于其它数据类型,它无能为力,你必须定义该函数额外的版本或
将它模板化。幸运的是,有一个更巧妙的办法来实现。

 

  创建和优化 vector

 

  每一个 STL 容器都具备一个分配器(allocator),它是一个内建的内存管理器,能
自动按需要重新分配容器的存储空间。因此,上面的程序可以得到大大简化,并摆脱  
reallocator 函数。

 

  第一步:创建 vector

 

  用 vector 对象取代内建的数组来保存获取的数据。main() 

 

中的循环读取 ISBN,检查

 

它是否为 0

 

,如果不为 0 

 

,则通过调用 push_back() 成员函数将值插入

vector

 

: #include <iostream>

#include <vector>
using namespace std;

int main()
{
 vector <int  

> vi;

 int isbn;
 while(true)
 {
  cout 

 

<< "enter an ISBN; press 0 to stop ";

  cin 

 

>> isbn;