a我考网

 找回密码
 立即注册

QQ登录

只需一步,快速开始

扫一扫,访问微社区

查看: 126|回复: 1

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

[复制链接]
发表于 2012-7-31 21:56:58 | 显示全部楼层 |阅读模式
 使用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
回复

使用道具 举报

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

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

p=temp; // reassign p to the newly allocated buffer  return 1;
6 Y- g6 b+ c/ z$ O$ r/ {9 m  }& j% m  \- V- r8 \
  int main(void)
9 B+ T7 A) t% w* a& K. L  {
3 _% x: y8 t$ a  int size=2; // 初始化数组大小;在运行时调整。
+ F; V" `4 H/ u( \+ H  int *p = new int[size];6 U# ^1 ]7 F: |, `
  int isbn;
2 m  z0 p% N: X* R, \2 U' b& s7 S  for(int n=0; ;++n)
5 g) B$ O! O8 A  {5 |9 B) J9 Z! H1 G0 Q6 z8 U; R9 \
  cout>isbn;
8 ^! X" W/ {0 |  if (isbn==0)2 Y2 U; |3 R$ S) Q0 _1 n' W
  break;
8 z7 D5 n1 t& l% ]& h  if (n==size) // 数组是否到达上限?
: i' w4 G0 P* Z  reallocate(p, size);
$ q  C) t9 ]  Y2 A7 A  W, O7 C  p[n]=isbn; // 将元素插入扩容的数组# ?# u/ N- S! X- U# @) ]3 N
  }6 J5 {2 ^1 m! z) k
  delete [] p; // 不要忘了这一步!
7 |# r. S7 e( a. ?" I: D  return 0;
6 r. T& i% e. ^6 M" h' t  }
回复 支持 反对

使用道具 举报

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

本版积分规则

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

GMT+8, 2024-6-17 17:17 , Processed in 0.351112 second(s), 24 queries .

Powered by Discuz! X3.4 Licensed

© 2001-2017 Comsenz Inc.

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