⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 stash4.cpp

📁 Thinking_in_C___2.rar
💻 CPP
字号:
//: C07:Stash4.cpp {O}
// From Thinking in C++, 2nd Edition
// at http://www.BruceEckel.com
// (c) Bruce Eckel 1999
// Copyright notice in Copyright.txt
// Function overloading
#include <cstdlib>
#include <cstring>
#include <cstdio>
#include "../require.h"
#include "Stash4.h"
using namespace std;

Stash::Stash(int Size) {
  size = Size;
  quantity = 0;
  next = 0;
  storage = 0;
}

Stash::Stash(int Size, int InitQuant) {
  size = Size;
  quantity = 0;
  next = 0;
  storage = 0;
  inflate(InitQuant);
}

Stash::~Stash() {
  if(storage) {
    puts("freeing storage");
    free(storage);
  }
}

int Stash::add(void* element) {
  if(next >= quantity) // Enough space left?
    inflate(100); // Add space for 100 elements
  // Copy element into storage,
  // starting at next empty space:
  memcpy(&(storage[next * size]),
         element, size);
  next++;
  return(next - 1); // Index number
}

void* Stash::fetch(int index) {
  if(index >= next || index < 0)
    return 0;  // Not out of bounds?
  // Produce pointer to desired element:
  return &(storage[index * size]);
}

int Stash::count() {
  return next; // Number of elements in Stash
}

void Stash::inflate(int increase) {
  void* v =
    realloc(storage, (quantity+increase)*size);
  require(v);  // Was it successful?
  storage = (unsigned char*)v;
  quantity += increase;
} ///:~

⌨️ 快捷键说明

复制代码 Ctrl + C
搜索代码 Ctrl + F
全屏模式 F11
切换主题 Ctrl + Shift + D
显示快捷键 ?
增大字号 Ctrl + =
减小字号 Ctrl + -