class Array {
public:
Array(unsigned len = 0) : length(len) {
data = (len ? new double[len] : nullptr);
}
private:
double *data; // array data
unsigned int length; // array size
}
You could use a struct, but users of your class would be able to access all member variables of your struct by default.
To copy the array, you need to perform a deep copy:
Array(const Array & a) {
length = a.getLength(); // getter for length // 1 step
data = new double[length]; // 1 step
for (unsigned i = 0; i < length; i++) { // n times
data[i] = a[i]; // c steps
}
}
The complexity of this is \(O(1 + 1 + (nc) + 1) = O(n)\)
void copyFrom(const Array & a) {
if (length != a.length) {
delete[] data;
length = a.length;
data = new double[length];
}
for (unsigned int i = 0; i < length; i++) {
data[i] = a.data[i];
}
}
Array(const Array & a) : length(0), data(nullptr) {
copyFrom(a);
}
Array & operator=(const Array & a) {
copyFrom(a);
return *this;
}
~Array() {
if (data != nullptr) {
for (int i = 0; i < length; i++) { // n times
delete data[i]; // 1 step
}
delete[] date; // 1 step
data = nullptr; // 1 step
}
}
Complexity: \(O(n)\)
operator[]
const double & operator[](int idx) const {
if (idx < length && idx >= 0)
return data[idx];
throw runtime_error("bad idx");
}
const
ostream &operator<<(ostream &os, const Array &a)
require const
.const double &operator()(int i, int j) const {
// return by const reference
}
operator[][]
bool insert(int index, double val) {
if (index >= size || index < 0) {
return false;
} else {
for (int i = size - 1; i > index; --i) {
data[i] = data[i - 1];
}
data[index] = val;
return true;
}
}
Complexity:
When array is full, resize
Copy n items from the original array to the new array
Appending n elements
ptr
to beginningcurrent_size
or ptr
max_size
or ptr
to end of allocated spacehead_ptr
to first nodesize
(optionaltail_ptr
to last nodeptr
to next nodeclass LinkedList {
public:
LinkedList();
~LinkedList();
private:
struct Node {
double item;
Node *next;
Node() {next = nullptr;}
};
Node *head_ptr;
};
int size() const;
bool append_item(double item);
bool append_node(Node *n);
bool delete_item(double item);
bool delete_node(Node *n);
start_ptr + size < end_ptr
nullptr