2014-06-23 4 views
4

내가 부스트 그래프 라이브러리를 사용하여 그래프를 정의,부스트 그래프 라이브러리를 사용하여 그래프의 가장자리 무게를 어떻게 변경합니까?

typedef boost::property<boost::edge_weight_t, int> EdgeWeightProperty; 
typedef boost::adjacency_list<boost::listS, boost::vecS,boost::undirectedS,boost::no_property,EdgeWeightProperty> Graph; 

이 일단 가장자리의 무게를 변경하는 방법을 알아 내기 위해

boost::add_edge(vertice1, vertice2, weight, graph); 

내가 아직 사용하여 가장자리를 추가 할 매우 간단합니다 설정되었습니다. 한 가지 가능한 해결책은 가장자리를 삭제하고 가중치 값이 업데이트 된 상태로 다시 추가하는 것입니다. 그러나 이는 과도한 것으로 보입니다.

답변

8

하나의 해결책은 속성 맵을 사용하는 것입니다 다음

typedef boost::adjacency_list<boost::setS, boost::vecS, boost::undirectedS,boost::no_property,EdgeWeightProperty> Graph; 
typedef Graph::edge_descriptor Edge; 
Graph g; 
std::pair<Edge, bool> ed = boost::edge(v1,v2,g); 
int weight = get(boost::edge_weight_t(), g, ed.first); 
int weightToAdd = 10; 
boost::put(boost::edge_weight_t(), g, ed.first, weight+weightToAdd); 
2

대체 솔루션을하는 것입니다. 여기에 예제가 있습니다.

// Edge weight. 
typedef boost::property<boost::edge_weight_t, int> EdgeWeightProperty; 

// Graph. 
typedef boost::adjacency_list< boost::listS, 
           boost::vecS, 
           boost::undirectedS, 
           boost::no_property, 
           EdgeWeightProperty > Graph; 

// Vertex descriptor. 
typedef typename boost::graph_traits<Graph>::vertex_descriptor Vertex; 

// The Graph object 
Graph g; 

// Populates the graph. 
Vertex v1 = boost::add_vertex(g); 
Vertex v2 = boost::add_vertex(g); 
Vertex v3 = boost::add_vertex(g); 
boost::add_edge(v1, v2, EdgeWeightProperty(2), g); 
boost::add_edge(v1, v3, EdgeWeightProperty(4), g); 
boost::add_edge(v2, v3, EdgeWeightProperty(5), g); 

// The property map associated with the weights. 
boost::property_map < Graph, 
         boost::edge_weight_t >::type EdgeWeightMap = get(boost::edge_weight, g); 

// Loops over all edges and add 10 to their weight. 
boost::graph_traits<Graph>::edge_iterator e_it, e_end; 
for(std::tie(e_it, e_end) = boost::edges(g); e_it != e_end; ++e_it) 
{ 
    EdgeWeightMap[*e_it] += 10; 
} 

// Prints the weighted edgelist. 
for(std::tie(e_it, e_end) = boost::edges(g); e_it != e_end; ++e_it) 
{ 
    std::cout << boost::source(*e_it, g) << " " 
      << boost::target(*e_it, g) << " " 
      << EdgeWeightMap[*e_it] << std::endl; 
} 
+0

무게가 가장자리의 소스 및 끝 정점의 함수 인 경우 어떻게됩니까? – Jim

+0

@ 짐 (Jim) 당신은 웨이트가 정점의 일부 변수 (예 : 상태)의 함수 인 경우 어떻게 될까요? 지금은 각 에지가 두 개의 노드에 연결되어 있기 때문에 가중치는 기술적으로 두 꼭지점의 함수입니다. "소스/타겟"순서가 중요하다면 양방향 그래프를 사용할 수 있습니다. – AntA