数组以某种方式被不使用数组的逻辑修改

时间:2014-11-18 22:54:05

标签: c++ arrays pointers kruskals-algorithm

我正在尝试用C ++构建Kruskal算法,并编写了部分内容,这里是代码:

#include <iostream>
#include <fstream>
#include <cstdio>
#include <cstdlib>
using namespace std;

class Edge {
    public:
        int to;
        int from;
        int weight;
        Edge();
        void print_edge();
};

Edge::Edge(void) {
}

void Edge::print_edge() {
    cout << "Edge to " << to << " from " << from << " of weight " << weight << endl;
}

int main() {
    int *vertex_sets;
    int vertex_size;
    int edge_size = 0;

    Edge* edges = new Edge[vertex_size * (vertex_size - 1) / 2];
    Edge* mst_edges = new Edge[vertex_size];

    cin >> vertex_size;
    vertex_sets = new int[vertex_size];

    for (int i = 0; i < vertex_size; i++) {
        int vertex_num;
        cin >> vertex_num;
        cout << "Assigning vertex set " << i << endl;
        vertex_sets[i] = i;
        int num_adjacent;
        cin >> num_adjacent;

        for (int j = 0; j < num_adjacent; j++) {
            edges[edge_size] = Edge();
            edges[edge_size].from = i;

            cin >> edges[edge_size].to >> edges[edge_size].weight;
            edge_size++;
        }
        cout << "Vertex " << i << " is in set " << vertex_sets[i] << endl;
        cout << "Vertex " << 0 << " is in set " << vertex_sets[0] << endl;
    }

    cout << endl;

    for (int i = 0; i < vertex_size; i++) {
        cout << "Vertex " << i << " is in set " << vertex_sets[i] << endl;
    }
}

但由于某种原因,vertex_sets数组在(int j = 0 ...循环期间发生变化,我不知道为什么会发生这种情况,因此打印语句。使用输入

8
0
2
4 2
5 6
1
1
6 1
2
2
3 2
4 2
3
4
2 2
4 3
6 5
7 4
4
3
0 2
2 2
3 3
5
2
0 6
6 2
6
3
1 1
3 5
5 2
7
1
3 4

我得到

的输出
Assigning vertex set 0
Vertex 0 is in set 0
Vertex 0 is in set 0
Assigning vertex set 1
Vertex 1 is in set 1
Vertex 0 is in set 0
Assigning vertex set 2
Vertex 2 is in set 2
Vertex 0 is in set 0
Assigning vertex set 3
Vertex 3 is in set 3
Vertex 0 is in set 3
Assigning vertex set 4
Vertex 4 is in set 4
Vertex 0 is in set 3
Assigning vertex set 5
Vertex 5 is in set 5
Vertex 0 is in set 3
Assigning vertex set 6
Vertex 6 is in set 6
Vertex 0 is in set 3
Assigning vertex set 7
Vertex 7 is in set 7
Vertex 0 is in set 3

Vertex 0 is in set 3
Vertex 1 is in set 2
Vertex 2 is in set 4
Vertex 3 is in set 3
Vertex 4 is in set 4
Vertex 5 is in set 5
Vertex 6 is in set 6
Vertex 7 is in set 7

这意味着由于某种原因,在循环的第四次迭代中,索引0处的vertex_sets的值从0变为3,我不明白为什么。有人能看出为什么会这样吗?

1 个答案:

答案 0 :(得分:1)

如果你使用一个未初始化的变量分配一个新数组,你将会遇到不好的时间。

Edge* edges = new Edge[vertex_size * (vertex_size - 1) / 2];
Edge* mst_edges = new Edge[vertex_size];

cin >> vertex_size;