使用C++ 實現(xiàn)緩存容量增加
出處:awey 發(fā)布于:2009-09-03 17:08:37
當你在某個緩存中存儲數(shù)據(jù)時,常常需要在運行時調(diào)整該緩存的大小,以便能容納更多的數(shù)據(jù)。
下面是一個增加初始緩存大小的例子:
view plaincopy to clipboardprint?
// console.cpp : Defines the entry point for the console application.
//
#include "stdafx.h"
#include <iostream>
#include <algorithm>
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; // 初始化數(shù)組大??;在運行時調(diào)整。
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) // 數(shù)組是否到達上限?
reallocate(p, size);
p[n]=isbn; // 將元素插入擴容的數(shù)組
}
delete [] p; // 不要忘了這一步!
return 0;
}
版權(quán)與免責聲明
凡本網(wǎng)注明“出處:維庫電子市場網(wǎng)”的所有作品,版權(quán)均屬于維庫電子市場網(wǎng),轉(zhuǎn)載請必須注明維庫電子市場網(wǎng),http://www.hbjingang.com,違反者本網(wǎng)將追究相關(guān)法律責任。
本網(wǎng)轉(zhuǎn)載并注明自其它出處的作品,目的在于傳遞更多信息,并不代表本網(wǎng)贊同其觀點或證實其內(nèi)容的真實性,不承擔此類作品侵權(quán)行為的直接責任及連帶責任。其他媒體、網(wǎng)站或個人從本網(wǎng)轉(zhuǎn)載時,必須保留本網(wǎng)注明的作品出處,并自負版權(quán)等法律責任。
如涉及作品內(nèi)容、版權(quán)等問題,請在作品發(fā)表之日起一周內(nèi)與本網(wǎng)聯(lián)系,否則視為放棄相關(guān)權(quán)利。
- EDA技術(shù)工具鏈與全流程設計運維指南2026/1/5 10:28:51
- PLC程序現(xiàn)場疑難問題排查與深度優(yōu)化指南2025/12/24 14:36:36
- PLC程序現(xiàn)場調(diào)試與優(yōu)化實操指南2025/12/24 14:29:57
- 工業(yè)PLC模擬量信號采集:調(diào)理技術(shù)與抗干擾工程方案2025/12/15 14:39:08
- PLC設備如何選型2025/9/5 17:15:14









