a我考网

 找回密码
 立即注册

QQ登录

只需一步,快速开始

扫一扫,访问微社区

查看: 135|回复: 1

[C++] 2011年计算机等级考试二级C++辅导实例编程(26)

[复制链接]
发表于 2012-7-31 21:56:58 | 显示全部楼层 |阅读模式
 使用C++ 实现缓存容量增加  当你在某个缓存中存储数据时,常常需要在运行时调整该缓存的大小,以便能容纳更多的数据。
: {, k$ W4 l# S  下面是一个增加初始缓存大小的例子:+ E. K% X" ~9 T( t6 {7 l
  view plaincopy to clipboardprint?
' |% _7 ?" T4 D  // console.cpp : Defines the entry point for the console application.7 l3 i: `8 _7 u6 @* F+ l4 g( G
  //  Z, U/ Q& o% _& F. T3 }% ~
  #include "stdafx.h"' E  B* ^% U- L7 F4 O; M, X
  #include' x: ^8 H1 Z. ]4 @3 L% e2 [
  #include# |1 N" \$ k2 K
  using namespace std;
  L9 R0 ~, A, p; u+ C  int reallocate(int* &p, int& size)' s7 B8 M$ j4 U4 ^$ H. W( t; W
  {
: S+ o! T6 N# G1 g& `  size*=2; // double the array''s size with each reallocation
; L# o) U' j% s) f# d3 ~+ k  int * temp = new int[size];
* U" {" R0 ~0 x0 _! \! o% W0 f  copy(p, p+(size/2), temp);0 a6 `, V8 A7 P
  delete [] p; // release original, smaller buffer
回复

使用道具 举报

 楼主| 发表于 2012-7-31 21:56:59 | 显示全部楼层

2011年计算机等级考试二级C++辅导实例编程(26)

p=temp; // reassign p to the newly allocated buffer  return 1;5 ~( y3 ?4 o, O6 a9 v5 U
  }- u) ]5 r" j- G/ j  ]7 X5 W& h- b* e; N+ \. @
  int main(void), p6 s+ N9 I8 z2 D- z6 ~
  {
. Z9 i: ~& X4 W  ?; ~, I2 k+ \  int size=2; // 初始化数组大小;在运行时调整。
2 L+ a9 m* T+ C. u7 a  int *p = new int[size];
6 k0 [6 l% b5 A* K% E# i- S: E  int isbn;9 I2 w& D8 I9 ]8 M) [, L, t; S
  for(int n=0; ;++n)
" m/ @! E2 ^! k# r0 ~  {
2 k( M- I1 @3 Q  cout>isbn;
' D9 h2 J" ]) |! s  if (isbn==0)4 k; f- f) L! j' ^8 w# e5 U+ _) v
  break;
" {( m7 b" v5 V1 I& v: _7 M& B* p1 r/ `& }  if (n==size) // 数组是否到达上限?
1 Z' W, z) {1 P6 Y, {  reallocate(p, size);
+ R* z' `. R* y# T  p[n]=isbn; // 将元素插入扩容的数组
' ~5 \0 X/ U$ R5 s  }
; A: ^# Q4 K( ~: v  delete [] p; // 不要忘了这一步!2 m1 C! X) ?) u2 e
  return 0;
. z9 O- j+ k, E  }
回复 支持 反对

使用道具 举报

您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

Archiver|手机版|小黑屋|Woexam.Com ( 湘ICP备18023104号 )

GMT+8, 2024-9-28 01:47 , Processed in 0.306755 second(s), 23 queries .

Powered by Discuz! X3.4 Licensed

© 2001-2017 Comsenz Inc.

快速回复 返回顶部 返回列表