[英]Find connected components using Boost Graph library, with the vertex and edge type being boost::listS
[英]Using boost graph library: how to create a graph by reading edge lists from file
我是 boost 圖形庫的新手,我想通過從文件中讀取邊列表來創建圖形。
edge_list.dat
文件的示例如下:
...
123 445
4535 343
3432 454
123 345
123 566
...
文件的每一行代表圖的一條邊,每行的兩個數字是邊對應的節點的id。 現在我想使用 boost 圖形庫從文件edge_list.dat
創建一個圖形。
但是,我事先不知道圖形的大小。 我需要沿途將頂點添加到圖中。 然而,像這樣為每個頂點創建一個頂點描述符是不切實際的:
Graph::vertex_descriptor v0 = boost::add_vertex(g);
Graph::vertex_descriptor v1 = boost::add_vertex(g);
我想通過頂點 id 訪問頂點。 我真的不知道該怎么做。 現在我想出的解決方案是創建一個映射,其鍵是 id 值是vertex_descriptor
:
std::map<int,Graph::vertex_descriptor> VertexList;
VertexList[123]=boost::add_vertex(g);
但是,有沒有一種方法可以在不創建地圖的情況下做到這一點?
提前致謝。
嗚嗚。 雄心勃勃,呵呵:)
Boost 圖庫。 和文本解析。 讓我們看看我們能做些什么:Boost Graph + Boost Spirit Qi = 良好的團隊合作。
#include <boost/fusion/adapted/std_pair.hpp>
#include <boost/spirit/include/qi.hpp>
#include <boost/graph/edge_list.hpp>
#include <fstream>
typedef std::pair<int,int> Edge;
typedef std::vector<Edge> EdgeList;
typedef boost::edge_list<EdgeList::iterator> Graph;
namespace qi = boost::spirit::qi;
int main()
{
std::ifstream ifs("input.txt");
ifs >> std::noskipws;
boost::spirit::istream_iterator f(ifs), l;
std::vector<Edge> edges;
bool parse_ok = qi::phrase_parse(f, l, (qi::int_ >> qi::int_) % qi::eol, qi::blank, edges);
Graph g(edges.begin(), edges.end());
if (parse_ok)
{
std::cout << "Graph parsed with " << num_edges(g) << " edges\n";
} else
std::cout << "Parse error\n";
if (f!=l)
std::cout << "Remaining unparsed input: '" << std::string(f,l) << "'\n";
}
打印(對於上面的有效輸入行):
Graph parsed with 5 edges
Remaining unparsed input: '
'
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.