我是图形和矢量的新手,我试图在图A,B,C等图上标记点。
class GraphMatrix
{
private:
int n;
int **adj;
bool *visited;
vector <string> label;
public:
GraphMatrix(const vector<string>&labels)
{
this->n = n;
visited = new bool [n];
adj = new int* [n];
for (int i = 0; i < n; i++)
{
adj[i] = new int [n];
for(int j = 0; j < n; j++)
{
adj[i][j] = 0;
}
}
}
bool add_edge(const string &origin, const string &destin)
{
int nodes;
vector<string>::iterator opos, dpos;
opos = std::find(label.begin(), label.end(), origin);
dpos = std::find(label.begin(), label.end(), destin);
if (opos == label.end() || dpos == label.end()) return false;
opos-label.begin();
}
/*
*/
void List()
{
int i,j, nodes;
for(i = 0; i < n; i++)
{
for(j = 0; j < n; j++)
{
cout << adj[i][j] << " ";
}
cout<<endl;
cout << "\nMatrix Graph\n" << endl;
for(int i = 0; i < nodes; i++)
{
cout << label[i] << " ";
}
cout << '\n';
for(int i = 0; i < nodes; i++)
{
cout << label[i] << "\n";
}
// assign labels to each node
// for ( int i = 1; i < nodes; i++ )
//{
// label [ i ] = label [ i - 1 ] + 1;
//}
}
}
};
int main()
{
string origin, destin;
int nodes, max_edges;
//char label[] = {'A', 'B', 'C', 'D', 'E'};
//label [ 0 ] = 'A';
vector<string> label;
cout << "How many points? ";
cin >> nodes;
cout << "Label the points: \n";
for(int i = 0; i < nodes; i++ )
{
cout << "Enter label for point # " << i << " ";
cin >> label[i];
}
GraphMatrix graph(label);
max_edges = nodes * (nodes - 1);
for (int i = 0; i < max_edges; i++)
{
cout << "Define edges between two points (q q to exit): ";
cin >> origin >> destin;
if((origin == "q") && (destin == "q"))
{
break;
}
graph.add_edge(origin, destin);
}
graph.List();
//system("pause");
return 0;
}
我的输出是:
How many points? 5
Label the points:
Enter label for point # 0 A
然后停止。
I am trying to get a graph that looks like this:
A B C D E
A 0 1 0 1 1
B 0 0 1 0 1
C 1 0 0 0 0
D 0 0 1 0 0
E 0 1 0 0 0
有人可以帮忙吗?我没有贴标签的图表打印很好。然后我尝试添加对我来说很新的向量,现在我无法让它工作。
答案 0 :(得分:0)
首先:
vector<string> label;
...
cin >> label[i];
Vector不知道你计划使用多少项,所以让我们声明一下:
label.resize(nodes); //now vector populated with 'nodes' default string
使用>>
的第二个问题是打算使用格式化的行,我假设您需要按 Enter 响应的内容,这就是使用getline
代替的原因:
getline(cin, label[i]);
第二:在图的构造函数中,您不初始化变量n
,而label
希望它应该是:
GraphMatrix(const vector<string>&labels):
n(labels.size()),
label(labels)
{
...
第三:add_edge
必须在结尾处返回
Forth:在list方法中,您可以使用变量i
和j
的名称来混合内部和外部循环来玩危险游戏。
经过一些修正后,你可以找到工作代码https://ideone.com/3yU9pw(带有创建边的样本[a b]和[c d])