使用C++实现缓存容量增加
来源:优易学  2010-1-14 19:27:32   【优易学:中国教育考试门户网】   资料下载   IT书店
  当你在某个缓存中存储数据时,常常需要在运行时调整该缓存的大小,以便能容纳更多的数据。
  下面是一个增加初始缓存大小的例子:
  view plaincopy to clipboardprint?
  // console.cpp : Defines the entry point for the console application.
  //
  #include "stdafx.h"
  #include
  #include
  using namespace std;
  int reallocate(int* &p, int& size)
  {
  size*=2; // double the array''s size with each reallocation
  int * temp = new int[size];
  copy(p, p+(size/2), temp);
  delete [] p; // release original, smaller buffer
  p=temp; // reassign p to the newly allocated buffer
  return 1;
  }
  int main(void)
  {
  int size=2; // 初始化数组大小;在运行时调整。
  int *p = new int[size];
  int isbn;
  for(int n=0; ;++n)
  {
  cout<< "enter an ISBN; press 0 to stop ";
  cin>>isbn;
  if (isbn==0)
  break;
  if (n==size) // 数组是否到达上限?
  reallocate(p, size);
  p[n]=isbn; // 将元素插入扩容的数组
  }
  delete [] p; // 不要忘了这一步!
  return 0;
  }

责任编辑:cyth

文章搜索:
 相关文章
热点资讯
资讯快报
热门课程培训