13.01.2015 Views

Pensar en C++ (Volumen 1) - Grupo ARCO

Pensar en C++ (Volumen 1) - Grupo ARCO

Pensar en C++ (Volumen 1) - Grupo ARCO

SHOW MORE
SHOW LESS

You also want an ePaper? Increase the reach of your titles

YUMPU automatically turns print PDFs into web optimized ePapers that Google loves.

✐<br />

✐<br />

✐<br />

“Volum<strong>en</strong>1” — 2012/1/12 — 13:52 — page 152 — #190<br />

✐<br />

Capítulo 4. Abstracción de Datos<br />

}<br />

storage = 0;<br />

next = 0;<br />

int Stash::add(const void* elem<strong>en</strong>t) {<br />

if(next >= quantity) // Enough space left<br />

inflate(increm<strong>en</strong>t);<br />

// Copy elem<strong>en</strong>t into storage,<br />

// starting at next empty space:<br />

int startBytes = next * size;<br />

unsigned char* e = (unsigned char*)elem<strong>en</strong>t;<br />

for(int i = 0; i < size; i++)<br />

storage[startBytes + i] = e[i];<br />

next++;<br />

return(next - 1); // Index number<br />

}<br />

void* Stash::fetch(int index) {<br />

// Check index boundaries:<br />

assert(0 = next)<br />

return 0; // To indicate the <strong>en</strong>d<br />

// Produce pointer to desired elem<strong>en</strong>t:<br />

return &(storage[index * size]);<br />

}<br />

int Stash::count() {<br />

return next; // Number of elem<strong>en</strong>ts in CStash<br />

}<br />

void Stash::inflate(int increase) {<br />

assert(increase > 0);<br />

int newQuantity = quantity + increase;<br />

int newBytes = newQuantity * size;<br />

int oldBytes = quantity * size;<br />

unsigned char* b = new unsigned char[newBytes];<br />

for(int i = 0; i < oldBytes; i++)<br />

b[i] = storage[i]; // Copy old to new<br />

delete []storage; // Old storage<br />

storage = b; // Point to new memory<br />

quantity = newQuantity;<br />

}<br />

void Stash::cleanup() {<br />

if(storage != 0) {<br />

cout

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!