So I have to write an operator= method in c++ that copies all the values of one array into another. Here's what I wrote:
dynamic_array &dynamic_array::operator=(const dynamic_array &a) {
size = a.get_size();
if (size % BLOCK_SIZE == 0){ //a multiple of BLOCK_SIZE
allocated_size = size;
} else {
int full_blocks = size / BLOCK_SIZE;
allocated_size = (full_blocks+1) * BLOCK_SIZE;
}
try {
array = new int[allocated_size];
} catch (bad_alloc){
throw exception (MEMORY_EXCEPTION);
}
//copy a[i..size-1]
for (int i = 0; i < size; i++){
array[i] = a[i];
}
return *this; //returns a reference to the object
}
So it doesn't assume anything about the sizes and sets the size and allocated size of the array it's given (and using another get_size() method). Now the second code I have to write just says I have to create an array containing a copy of the elements in a. Now I just wrote the same thing as I did for my operator= method (without returning anything):
dynamic_array::dynamic_array(dynamic_array &a) {
size = a.get_size();
if (size % BLOCK_SIZE == 0){ //a multiple of BLOCK_SIZE
allocated_size = size;
} else {
int full_blocks = size / BLOCK_SIZE;
allocated_size = (full_blocks+1) * BLOCK_SIZE;
}
try {
array = new int[allocated_size];
} catch (bad_alloc){
throw exception (MEMORY_EXCEPTION);
}
//copy a[i..size-1]
for (int i = 0; i < size; i++){
array[i] = a[i];
}
}
Now this is giving me the output that I want but I'm just wondering if there's an easier way to do these two methods. The methods are for a dynamic array and I feel like there's more lines of code than needed. The operator= one is supposed to copy the elements of a into a new dynamic array and dynamic_array::dynamic_array(dynamic_array &a) {
is supposed to create a new array containing a copy of the elements in a. It sounds like the same code for each method because you always need to create a new array and you will always need to copy the array elements from one array to another but is there a more simpler way to write these two methods or is this the simplest way to do it?