使用 stl 库创建图形是如何工作的?

How does this creation of graph using stl library work?

本文关键字:工作 何工作 stl 创建 图形 使用      更新时间:2023-10-16

我对下面给出的这句代码的一行有疑问:

cout<<"("<<c<<","<<(*i).get_vertex()<<") value of this pair : "<<(*i).get_weight()<<", ";

这get_vertex和get_weight如何在没有类边缘对象帮助的情况下工作。代码编译成功,它也在工作,但我无法弄清楚上面的行是如何工作的。

代码的输出为:

Pairs for 0 are -> (0,1) value of this pair : 2, (0,2) value of this pair : 3, (0,3) value of this pair : 4,
Pairs for 1 are -> (1,2) value of this pair : 5, (1,0) value of this pair : 2,
Pairs for 2 are -> (2,3) value of this pair : 8, (2,1) value of this pair : 5,
Pairs for 3 are -> (3,0) value of this pair : 4, (3,2) value of this pair : 8,

代码给出如下:

#include<bits/stdc++.h>
using namespace std;
class edge{
int weight,vertex;
public:
edge(int w , int v){
weight = w;
vertex = v;
}
int get_weight()const{
return weight;
}
int get_vertex()const{
return vertex;
}

};

int main(){
int n = 4;
int c = 0;
vector<list<edge>>adj(n) ;
adj[0].push_back(edge(2,1));
adj[0].push_back(edge(3,2));
adj[0].push_back(edge(4,3));

adj[1].push_back(edge(5,2));
adj[1].push_back(edge(2,0));

adj[2].push_back(edge(8,3));
adj[2].push_back(edge(5,1));
adj[3].push_back(edge(4,0));
adj[3].push_back(edge(8,2));

vector<list<edge>>:: iterator it ;
for(it=adj.begin();it!=adj.end();it++){
cout<<" Pairs for "<<c<<" are -> ";
list<edge>li = *it;
list<edge>::iterator i;
for(i=li.begin();i!=li.end();i++){
cout<<"("<<c<<","<<(*i).get_vertex()<<") value of this pair : "<<(*i).get_weight()<<", ";
}
cout<<endl;
c++;
}

}

将其分解为块。 添加空格:

cout << "(" 
<< c 
<< "," 
<< (*i).get_vertex() 
<< ") value of this pair : "
<< (*i).get_weight()
<< ", ";

这更有意义吗?