boost库之graph入门

#include <boost/graph/undirected_graph.hpp>
#include <boost/graph/adjacency_list.hpp>
using namespace std;

int _tmain(int argc, _TCHAR* argv[])
{
	// 创建简单无向图
	//typedef boost::adjacency_list<boost::lists boost::undirecteds="" boost::vecs=""> Graph;
	/*
	Graph g;
	// 添加边
     	boost::add_edge(0, 1, g);
	boost::add_edge(0, 3, g);
	boost::add_edge(1, 2, g);
	boost::add_edge(2, 3, g);

	cout << "Number of edges: " << boost::num_edges(g) << endl;// 边的数量
	cout << "Number of vertices: " << boost::num_vertices(g) << endl;// 顶点的数量


	Graph::vertex_iterator vertexIt,vertexEnd;// 顶点
	Graph::adjacency_iterator neighbourIt, neighbourEnd;// 邻接边

	boost::tie(vertexIt, vertexEnd) = boost::vertices(g);
	for (; vertexIt != vertexEnd; ++vertexIt) {
		std::cout << "edge vertex " << *vertexIt << std::endl;
		// 输出顶点的入边
		Graph::in_edge_iterator inedgeIt, inedgeEnd;

		boost::tie(inedgeIt, inedgeEnd) = boost::in_edges(*vertexIt, g);
		std::cout << "in edge: ";
		for (; inedgeIt != inedgeEnd; ++inedgeIt) {
			std::cout << *inedgeIt << " ";
		}
		std::cout << std::endl;


		// 输出顶点的出边
		Graph::out_edge_iterator outedgeIt, outedgeEnd;

		boost::tie(outedgeIt, outedgeEnd) = boost::out_edges(*vertexIt, g);
		std::cout << "out edge: ";
		for (; outedgeIt != outedgeEnd; ++outedgeIt) {
			std::cout << *outedgeIt << " ";
		}
		std::cout << std::endl;
	}
	*/


	// 创建无向图,并使用顶点和边的属性
	// 顶点属性
	typedef boost::property<boost::vertex_name_t std::string=""> VertexNameProp;
	// 边属性
	typedef boost::property<boost::edge_weight_t int=""> EdgeWeightProp;
	// 图
	typedef boost::adjacency_list<boost::lists boost::vecs="" boost::undirecteds="" vertexnameprop="" edgeweightprop=""> Graph;

	Graph g;
	std::string citys[4] = {"北京", "上海", "武汉", "西安"};
	Graph::vertex_descriptor v[4];
	// 添加顶点
	v[0] = boost::add_vertex(citys[0], g);
	v[1] = boost::add_vertex(citys[1], g);
	v[2] = boost::add_vertex(citys[2], g);
	v[3] = boost::add_vertex(citys[3], g);
	// 添加边
	boost::add_edge(v[0], v[1], 10, g);
	boost::add_edge(v[0], v[2], 40, g);
	boost::add_edge(v[0], v[3], 50, g);

	Graph::vertex_iterator vertexIt, vertexEnd;
	// 顶点的属性
	boost::property_map<graph boost::vertex_name_t="">::type vertexprop = boost::get(boost::vertex_name, g);
	// 边的属性
	boost::property_map<graph boost::edge_weight_t="">::type edgeprop = boost::get(boost::edge_weight, g);

	boost::tie(vertexIt, vertexEnd) = boost::vertices(g);
	for (; vertexIt != vertexEnd; ++vertexIt) {
		// 获取顶点属性
		std::string vprop = vertexprop[*vertexIt];
		// 设置顶点的属性 
		//vertexprop[*vertexIt] = "";
	
		Graph::out_edge_iterator outedgeIt, outedgeEnd;
		// 设置边属性
		boost::tie(outedgeIt, outedgeEnd) = boost::out_edges(*vertexIt, g);
		for (; outedgeIt != outedgeEnd; ++outedgeIt) {
			edgeprop[*outedgeIt] = 100;
		}
	}
}

posted on 2014-10-03 21:25  dchao  阅读(1943)  评论(0编辑  收藏  举报

导航