C++ 创建基于用户的图形
我是图表科的新手。我最近试着写一个程序,这个程序将获取顶点数、边数和顶点之间的连接数C++ 创建基于用户的图形,c++,graph,C++,Graph,我是图表科的新手。我最近试着写一个程序,这个程序将获取顶点数、边数和顶点之间的连接数 #include<iostream> #include<queue> #include<vector> using namespace std ; void add_edge(vector<int> adj[] , int v1 , int v2 ) { adj[v1].push_back(v2); adj[v2].push_back(v1);
#include<iostream>
#include<queue>
#include<vector>
using namespace std ;
void add_edge(vector<int> adj[] , int v1 , int v2 )
{
adj[v1].push_back(v2);
adj[v2].push_back(v1);
}
void print_graph ( vector<int>adj[] , int vertices)
{
for(int i = 0 ; i < vertices ; i++)
{
cout<< "adjacency list of vertex " << i << " is : \n" ;
cout<< "head -> " ;
for(auto it = adj[i].begin() ; it != adj[i].end() ; it++)
{
cout << *it << " -> " ;
}
cout<< "\n" ;
}
}
int main()
{
int ver , ed , i , j , s , v1 , v2 , temp ;
cin >> ver >> ed ;
vector<int> adj[ver] ;
for(i = 0 ; i < ver ; i++)
{
cin>> v1 ;
for(i = 0 ; i < ed ; i++)
{
cin >> v2 ;
char ch = (char)v2 ;
if (v2 == '\n')
{
break ;
}
add_edge(adj , v1 , v2 ) ;
}
}
print_graph(adj , ver);
return 0 ;
}
但整个程序无法正常运行。请帮我弄清楚 您将变量
i
用于两个循环。在内部for
循环之后,i
将始终等于ed
,如果该值小于ver
,则处于无止境的循环中
为内部循环使用不同的变量,例如,您已经定义的j
:
for (j = 0; j < ed; j++)
(j=0;j
还请注意,虽然允许您将
v2
与'\n'
进行比较,但这不会检查用户是否按了enter键。而是将v2
与换行字符的ASCII值进行比较(即10
)。您可以更改分隔符,例如,仅在换行符处停止输入,请参阅。什么工作不正常?预期会发生什么,实际发生了什么?只要告诉我当我必须按enter键打破循环时该怎么做。@MD.MarufHasam您需要更详细地描述您想要做什么。使用我的修复,当输入指定数量的顶点和边时,for循环将自动中断。如果要在回车时打断,为什么最初要询问顶点和边的数量?
for (j = 0; j < ed; j++)