یک راه خوب و ساده استفاده از map هستش به این شکل :
struct Node
{
Node(const std::string& name, int weight) :
name_(name),
weight_(weight){}
std::string name_;
int weight_;
};
using Graph =std::map < Node, std::map< Node,int>>;
مثال از استفاده : (اجرا زنده )
#include <iostream>
#include <map>
#include <string>
struct Node
{
Node(const std::string& name, int weight) :
name_(name),
weight_(weight){}
std::string name_;
int weight_;
};
bool operator<(const Node& lhs, const Node& rhs){
return lhs.name_ < rhs.name_;
}
using Graph = std::map < Node, std::map< Node, int>>;
int main()
{
Graph graph;
Node A("A", 3);
Node B("B", 1);
Node C("C", 4);
graph[A][B] = 5;
graph[A][C] = 1;
graph[B][C] = 7;
std::cout << graph[A][C]<<'\n'; //inja weight edge(A,C) yani 1 chap mishe
//Chap ras haye motasel be A
auto& connected= graph[A];
for (auto& edge_weight : connected){
std::cout << "Edge : (" << A.name_ << "," <<
edge_weight.first.name_ << ") Weight : " <<
edge_weight.second << '\n';
}
}