+ 1

Is there a better solution to this problem?

In the C++ course under "More On Classes", the module at the end "Queue Management Part 2" asks to add two objects of queue class. This was my solution: Queue operator +(Queue& obj) { Queue totalQ; // Create an object of Queue class to store the new queue // Copy the elements from the first queue to the beginning of the new one for (int i = 0; i < this->size; i++) { totalQ.queue[i] = this->queue[i]; totalQ.size += 1; } // Copy the elements from the second queue after the ones of the first queue for (int i = totalQ.size; i < (obj.size * 2); i++) { totalQ.queue[i] = obj.queue[i - 4]; totalQ.size += 1; } return totalQ; }

3rd Apr 2021, 8:16 PM
Diego Nogueras
1 ответ
+ 3
My solution is less code but shouldn't perform much faster: Queue operator+(const Queue& other) { Queue result; for (int i = 0; i < this->size;i++) { result.add(this->queue[i]); } for (int i = 0; i < other.size;i++) { result.add(other.queue[i]); } return result; } It is a little odd to optimize for speed in this situation since there isn't much need. Optimizations will make the code less readable and harder to maintain without much practical benefit. If you were in a situation where that operator+ implementation was causing serious problems, you could speed it up, though. c++ has a memcpy function that would copy all data from one queue to another in less time. More detail on that is here: http://www.cplusplus.com/reference/cstring/memcpy/ Here is a solution using memcpy: Add this to the top: #include <cstring> Here is the code: Queue operator+(const Queue& other) { Queue result; result.size = this->size + other.size; // in case resulting size is larger than allocated memory, replace block of memory. delete [] result.queue; // avoid memory leak result.queue = new int[result.size]; memcpy(result.queue, this->queue, sizeof(int) * this->size); memcpy(result.queue + this->size, other.queue, sizeof(int) * other.size); return result; } It should perform a little better since memcpy is heavily optimized but it is a good practice to benchmark and measure the performance difference any time you optimize. I didn't time this because I wanted to share the idea for educational purposes. If you were working on professional software, either you need the optimization badly enough to sacrifice code clarity and the time to test for performance or you shouldn't make the change at all.
3rd Apr 2021, 8:46 PM
Josh Greig
Josh Greig - avatar