2017年計(jì)算機(jī)二級C++輔導(dǎo)編程:使用C++ 實(shí)現(xiàn)緩存容量增加

字號:


    使用C++ 實(shí)現(xiàn)緩存容量增加
    當(dāng)你在某個緩存中存儲數(shù)據(jù)時,常常需要在運(yùn)行時調(diào)整該緩存的大小,以便能容納更多的數(shù)據(jù)。
    下面是一個增加初始緩存大小的例子:
    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; // 初始化數(shù)組大小;在運(yùn)行時調(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ù)組是否到達(dá)上限?
    reallocate(p, size);
    p[n]=isbn; // 將元素插入擴(kuò)容的數(shù)組
    }
    delete [] p; // 不要忘了這一步!
    return 0;
    }