C++ 对于循环更改数组';s值,单位为c++;
我有一个图形表示,我想做一个数组来保持索引 下面是一个小测试:C++ 对于循环更改数组';s值,单位为c++;,c++,arrays,for-loop,graph,C++,Arrays,For Loop,Graph,我有一个图形表示,我想做一个数组来保持索引 下面是一个小测试: int main() { Graph g1(5); g1.addEdge(1, 1); g1.addEdge(1, 2); g1.addEdge(1, 3); g1.addEdge(2, 3); g1.addEdge(3, 1); g1.addEdge(3, 2); g1.addEdge(3, 5); g1.addEdge(5, 4); cout<
int main()
{
Graph g1(5);
g1.addEdge(1, 1);
g1.addEdge(1, 2);
g1.addEdge(1, 3);
g1.addEdge(2, 3);
g1.addEdge(3, 1);
g1.addEdge(3, 2);
g1.addEdge(3, 5);
g1.addEdge(5, 4);
cout<<g1.array[0]<<endl;
cout<<g1.array[1]<<endl;
cout<<g1.array[2]<<endl;
cout<<g1.array[3]<<endl;
cout<<g1.array[4]<<endl;
for (int i = 0; i < g1.V ; i++) {
cout<<g1.array[i]<<endl;
}
cout<<g1.array[4]<<endl;
return 0;
}
问题来自您的阵列。事实上,在C++中,数组必须是固定大小的,并且它们不能动态增长。因此,您的代码具有未定义的行为 要解决此问题,请将
图形中的数组替换为:
矢量阵列//你能给我们看一下图表吗?数组的大小有点问题。我看到了两张接近的选票,因为不会有MCVE。但是自从编辑了这个问题,所有需要重现错误的东西都在这里!
values
2
2
2
1
1
entering for loop
2
2
2
1
4 <<< 1 is expected for the last item
loop ended
5 <<< 1 is still expected for last item - but why isn't it 4 anymore?
class Graph
{
//int V; // No. of vertices
list<int> *adj; // A dynamic array of adjacency lists
// A Recursive DFS based function used by SCC()
void SCCUtil(int u, int disc[], int low[],
stack<int> *st, bool stackMember[]);
void topologicalSortUtil(int v, bool visited[], stack<int> &Stack);
public:
int V;
int array [];
Graph(int V); // Constructor
void addEdge(int v, int w); // function to add an edge to graph
void SCC(); // prints strongly connected components
void topologicalSort();
};
Graph::Graph(int V)
{
array[V];
this->V = V;
adj = new list<int>[V];
}
void Graph::addEdge(int v, int w)
{
adj[v-1].push_back(w-1);
array[w-1]++;
}
vector<int> array; //<==== better definition than in array[];
array.resize(V); //<===== instead of array[V] which only accesses a non existing element