
使用C++ 实现缓存容量增加
当你在某个缓存中存储数据时,常常需要在运行时调整该缓存的大小,以便能容纳更多的数据。
下面是一个增加初始缓存大小的例子:
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;
}
2017年计算机二级C++辅导编程:使用C++ 实现缓存容量增加.doc正在阅读:
2017年计算机二级C++辅导编程:使用C++实现缓存容量增加08-20
2020年选调生公共基础政治常识:矛盾的含义及基本属性01-04
小学五年级下册语文课件:《与象共舞》05-12
小学教师年度考核个人总结德能勤绩廉-优秀教师年度考核个人总结德能勤绩廉08-15
基层民警入党申请格式01-12
中考优秀作文范文:保护环境从我做起10-24