Hey guys, I'm currently working with my friend on an assignment which we need to find the shortest path to each point by using prim's algorithm. And here is our work:
And the rest are my friend's work. The output for our code seems to look corrected, but after we press any key to exist the execution, it pop up a message says there is a breakpoint for our code.
Can someone help us with this problem? Really appreciated!
Thanks for the reply.
The problem is that our professor dose not allow us to use vector or anything provided by STL to this assignment. So is there any other solution for that?
Darn, I was looking through the code and didn't spot the obvious :P
So since helios probably found the problem, just want to add that if you're in debug mode in visual studio, a break point can mean that runtime routines found heap corruption.
Since you're working with dynamic arrays (int* var = new int[...]), my initial guess was that you're going out of bounds in your array iterations. (which is in fact the problem)
If I compile with errors, note that you never use the variable "count" on line 45. Not sure if this is intentional.
Here's some other notes:
1 2 3 4 5 6 7 8 9 10 11 12
while (1) {
int n;
stream >> n;
if (!stream) {
break;
}
max_vertex = n;
if (max_vertex > total_vertex) {
total_vertex = max_vertex;
max_vertex = 0;
}
}
can be slightly shorted as
1 2 3 4 5 6 7 8
int n;
while (stream >> n) {
max_vertex = n;
if (max_vertex > total_vertex) {
total_vertex = max_vertex;
max_vertex = 0;
}
}
I recommend that you create a class that behaves like an automatically resized array, which is how you assumed new T[total_vertex] would behave when you wrote your code. I'll just give you the class declaration:
template <typename T>
class DynamicArray{
T *data = nullptr;
size_t size = 0;
public:
DynamicArray() = default;
//Sets element i of the array to value val. If the internal array is too small it grows it
//and fills any intermediate elements with zeroes.
//For example:
//DynamicArray<int> a;
//(a = [])
//a.set(0,1);
//(a = [1])
//a.set(3, 2);
//(a = [1, 0, 0, 2])
void set(size_t i, const T &val);
//Returns element i of the array. I recommend checking that the index is valid and
//throwing an exception if it's not.
const T &get(size_t i);
};
Remember that to "grow" an array you need to allocate a larger array and copy the contents of the old one to it, then release the old array.