Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #ifndef INTCOLLECTION_H
- #define INTCOLLECTION_H
- // Allocate memory in chunks of ints of this size.
- const int CHUNK_SIZE = 5;
- class IntCollection
- {
- private:
- // The number of ints currently stored in the int
- int size;
- // the total number of elements available for storage
- // in the data array
- int capacity;
- // A pointer to the dynamically allocated data array
- int* data;
- // a private member function to allocate more memory
- // if necessary
- void addCapacity();
- public:
- // Constructor
- IntCollection();
- // Destructor
- ~IntCollection();
- // Copy constructor:
- IntCollection(const IntCollection &c);
- void add(int value);
- int get(int index);
- int getSize();
- IntCollection& operator=(const IntCollection &c);
- bool operator==(const IntCollection &c);
- IntCollection& operator<<(int value);
- };
- #endif
- #include "IntCollection.h"
- #include <iostream>
- #include <cstdlib>
- using namespace std;
- IntCollection::IntCollection()
- {
- // Initialize member data to reflect an empty
- // IntCollection
- size = capacity = 0;
- data = NULL;
- }
- IntCollection::~IntCollection()
- {
- delete [] data;
- }
- IntCollection::IntCollection(const IntCollection &c)
- {
- size = c.size;
- capacity = c.capacity;
- data = c.data;
- for(int i = 0; i < c.size; i++)
- {
- data[i] = c.data[i];
- }
- }
- void IntCollection::addCapacity()
- {
- // Create a new, bigger buffer, copy the current data to
- // it, delete the old buffer, and point our data
- // pointer to the new buffer
- int *newData;
- data = new int[capacity];
- capacity += CHUNK_SIZE;
- newData = new int[capacity];
- for(int i = 0; i < size; i++)
- {
- newData[i] = data[i];
- delete [] data;
- data = newData;
- }
- }
- void IntCollection::add(int value)
- {
- //first, allocate more memory if we need to
- if(size == capacity)
- {
- addCapacity();
- }
- //Now, add the data to our array and increment size
- data[size++] = value;
- }
- int IntCollection::get(int index)
- {
- if (index < 0 || index >= size)
- {
- cout << "ERROR: get() trying to access index out of range.n";
- exit(1);
- }
- return data[index];
- }
- int IntCollection::getSize()
- {
- return size;
- }
- IntCollection& IntCollection::operator=(const IntCollection &c)
- {
- size = c.size;
- capacity = c.capacity;
- data = c.data;
- return *this;
- }
- bool IntCollection::operator==(const IntCollection &c)
- {
- if((size == c.size) && (capacity == c.capacity))
- {
- for(int m = 0; m < size; m++)
- {
- if(data[m] == c.data[m])
- {
- continue;
- }
- else
- {
- return false;
- }
- }
- }
- return true;
- }
- IntCollection& IntCollection::operator<<(int value)
- {
- return value; <-- THIS IS WHERE I GET LOST!
- }
Add Comment
Please, Sign In to add comment