使用C++ 实现缓存容量增加 当你在某个缓存中存储数据时,常常需要在运行时调整该缓存的大小,以便能容纳更多的数据。
q8 ^! g: q+ l& s( m' B# }! u. v 下面是一个增加初始缓存大小的例子:
/ \1 L& N+ d# d( L) G view plaincopy to clipboardprint?3 _3 V5 I9 ?$ k) ]2 m% y k
// console.cpp : Defines the entry point for the console application.
6 I7 Y* }" `, u$ @. J& Z" @ //
% ]/ @0 H' G: Y7 U9 s$ j2 C #include "stdafx.h"6 ]& W& S: R5 R
#include
( Y* e; i" q, I1 a! V& D #include
- T2 R1 |4 S$ Q0 e8 \ using namespace std;# [; Z+ ~- d3 h4 U* J+ v% o& x: W
int reallocate(int* &p, int& size)
3 @. i) F; w) C( z" m. P {
0 l0 L5 k) C4 G. a: h4 ] size*=2; // double the array''s size with each reallocation# E- K) S1 c! k% N/ N
int * temp = new int[size];
2 ~* ?# G9 X6 q0 j$ c copy(p, p+(size/2), temp);
/ o: t0 y! } b" N* D delete [] p; // release original, smaller buffer |