Skip to content

Instantly share code, notes, and snippets.

@lukaskonarovsky
Created April 6, 2009 21:33
Show Gist options
  • Save lukaskonarovsky/90951 to your computer and use it in GitHub Desktop.
Save lukaskonarovsky/90951 to your computer and use it in GitHub Desktop.
C++ dynamic array implementation
#include "dynamicarray.h"
using namespace std;
DynamicArray::DynamicArray() {
DynamicArray::DynamicArray(5);
}
DynamicArray::DynamicArray(int initSize) {
size = initSize;
array = new int[size];
for (int i = 0; i < size; i++) {
array[i] = 0; // Fill with zeroes
}
}
DynamicArray::DynamicArray(const DynamicArray &original) {
size = original.size;
array = new int[size];
for (int i = 0; i < size; i++) {
array[i] = original.array[i];
}
}
DynamicArray::~DynamicArray() {
delete[] array;
}
void DynamicArray::insert(int position, int value) {
array[position] = value;
}
int DynamicArray::get(int position) {
return array[position];
}
int DynamicArray::getSize() {
return size;
}
void DynamicArray::resize(int newSize) {
int *temp;
temp = new int[newSize];
for (int i = 0; i < (newSize); i++) {
temp[i] = array[i];
}
delete[] array;
array = temp;
size = newSize;
}
bool DynamicArray::operator==(DynamicArray a) {
if (a.size != size) return false;
for (int i = 0; i < (a.size); i++) {
if (a[i] != array[i]) return false;
}
}
bool DynamicArray::operator!=(DynamicArray a) {
if (a.size != size) return true;
for (int i = 0; i < (a.size); i++) {
if (a[i] != array[i]) return true;
}
}
int &DynamicArray::operator[](int index) {
if ((index - 1) > size) {
resize(index + 1);
}
return array[index]; // returned as a reference
}
class DynamicArray {
public:
DynamicArray();
DynamicArray(int initSize);
DynamicArray(const DynamicArray &original);
~DynamicArray();
void insert(int position, int value);
int get(int position);
int getSize();
void resize(int newSize);
int &operator[](int index);
bool operator==(DynamicArray);
bool operator!=(DynamicArray);
private:
int size;
int *array;
};
#include <iostream>
#include "dynamicarray.h"
using namespace std;
int main(int argc, char **argv) {
cout << "Dynamic array..." << endl;
DynamicArray array = DynamicArray(4);
array.insert(1, 7);
array.insert(3, 2);
array[2] = 4;
array[10] = 4;
cout << "Pole naplněno." << endl;
DynamicArray array2 = DynamicArray(array);
if (array == array2) {
cout << "Kopírovací konstruktor a porovnávání funguje." << endl;
}
array[1] = 9999111;
if (array != array2) {
cout << "Pole jsou správně považována za nestejná." << endl;
}
return 0;
}
@Darklanx
Copy link

don't you have to add an else statement that return true after operator== and return false after operator!=?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment