I will be using your answer to compare to my own answer I have completed, any he
ID: 3567854 • Letter: I
Question
I will be using your answer to compare to my own answer I have completed, any help would truly be helpful. Thank you in advance!
// List.cpp
#include "List.h"
List::List(size_t capacity)
{
data_ = new int[capacity];
capacity_ = capacity;
size_ = 0;
}
List::List(const List &list)
{
copy(list);
}
List::~List()
{
delete[] data_;
}
void List::copy(const List &list)
{
size_t i;
size_ = list.size_;
capacity_ = list.capacity_;
data_ = new int[list.capacity_];
for (i = 0; i data_[i] = list.data_[i];
}
}
List& List::operator=(const List &list)
{
if (&list != this) {
// deallocate existing dynamic array
delete[] data_;
// copy the data
copy(list);
}
return *this;
}
List& List::operator+=(const List &list)
{
size_t i;
size_t pos = size_;
if ((size_ + list.size_) > capacity_) {
resize(size_ + list.size_);
}
for (i = 0; i data_[pos++] = list.data_[i];
}
size_ += list.size_;
return *this;
}
void List::append(int item)
{
if (size_ == capacity_) {
resize(2 * capacity_);
}
data_[size_++] = item;
}
void List::resize(size_t new_size)
{
int *temp;
size_t i;
capacity_ = new_size;
temp = new int[capacity_];
for (i = 0; i temp[i] = data_[i];
}
delete[] data_;
data_ = temp;
}
// List.h
#ifndef _LIST_H_
#define _LIST_H_
#include
class List {
public:
List(size_t capacity = 10); // constructor - allocates dynamic array
List(const List &a); // copy constructor
~List(); // destructor
int& operator[](size_t pos); // bracket operator
List& operator=(const List &a); // assignment operator
List& operator+=(const List &a); // += operator
void append(int item);
size_t size() const { return size_; }
private:
void copy(const List &a);
void resize(size_t new_size); // allocate new larger array
int *data_; // dynamic array
size_t size_; // size of dynamic array
size_t capacity_; // capacity of dynamic array
};
inline int& List::operator[](size_t pos)
{
return data_[pos];
}
#endif // _LIST_H_