Created
November 4, 2010 09:50
-
-
Save chtitux/662287 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <iostream> | |
#include <sstream> | |
#include <string> | |
#include <stdexcept> | |
#include "dynamicarray.h" | |
const unsigned int DynamicArray::BLOCK_SIZE = 10; | |
DynamicArray::DynamicArray(): | |
array(allocate(blockSize())), length(blockSize()) | |
{ | |
} | |
DynamicArray::DynamicArray(int _length): | |
array(allocate(_length)), length(_length) | |
{ | |
} | |
DynamicArray::DynamicArray(const DynamicArray &da): | |
array(allocate(da.length)),length(da.length) | |
{ | |
for( int i = 0; i < length; i++) | |
{ | |
set(i, da.get(i)); | |
} | |
} | |
int DynamicArray::blockSize() const { | |
return DynamicArray::BLOCK_SIZE; | |
} | |
std::ostringstream& DynamicArray::printOn(std::ostringstream & os) { | |
os << "["; | |
for (int i = 0; i < length; i++) { | |
os << array[i] << " "; | |
} | |
os << "]"; | |
return os; | |
} | |
int DynamicArray::size() const { | |
return length; | |
} | |
void DynamicArray::set(int pos, int value) { | |
assertIndex(pos); | |
array[pos] = value; | |
} | |
int DynamicArray::get(int pos) const { | |
assertIndex(pos); | |
return array[pos]; | |
} | |
void DynamicArray::grow() { | |
int* newarray = allocate(length + blockSize()); | |
for(int i = 0; i < length; i++) | |
{ | |
newarray[i] = get(i); | |
} | |
length += blockSize(); | |
array = newarray; | |
} | |
int* DynamicArray::allocate(unsigned int size) const { | |
int* newarray = new int[size]; | |
for(unsigned int i = 0; i < size; i++) | |
{ | |
newarray[i] = 0; | |
} | |
return newarray; | |
} | |
void DynamicArray::assertIndex(int pos) const | |
{ | |
if (pos > length || pos < 0) | |
throw std::out_of_range("Position hors tableau"); | |
} | |
int & DynamicArray::operator [](int pos){ | |
return array[pos]; | |
} | |
DynamicArray & DynamicArray::operator =(DynamicArray & da){ | |
return *(new DynamicArray(da)); | |
} | |
DynamicArray::~DynamicArray() | |
{ | |
if(array != NULL) | |
delete [] array; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment