以下代码未编译。
#include <boost/graph/adjacency_list.hpp>
#include <boost/graph/topological_sort.hpp>
#include <boost/function_output_iterator.hpp>
typedef boost::adjacency_list<
boost::setS, // outedge list
boost::setS, // vertex list
boost::directedS, // undirected
boost::no_property, // vertex prop
boost::no_property, // edge prop
boost::no_property, // graph prop
boost::setS // edgelist
> Graph;
bool hasCycle(const Graph& aG)
{
try {
boost::topological_sort(
aG,
boost::make_function_output_iterator([](int){}));
} catch(boost::not_a_dag const&)
{
return true;
}
return false;
}
将顶点列表更改为vecS后,它可以正常工作 http://coliru.stacked-crooked.com/a/abeb9e3f96e92af0
这是因为DFS需要确定性访问吗?
谢谢,
答案 0 :(得分:2)
“限制”被记录为需要顶点索引。您可以添加一个(请注意,您还应该int
替换Graph::vertex_descriptor
),或者调整图表类型以包含一个:
<强> Live On Coliru 强>
#include <boost/graph/adjacency_list.hpp>
#include <boost/graph/topological_sort.hpp>
#include <boost/function_output_iterator.hpp>
typedef boost::adjacency_list<
boost::setS, // outedge list
boost::setS, // vertex list
boost::directedS, // undirected
boost::no_property, // vertex prop
boost::no_property, // edge prop
boost::no_property, // graph prop
boost::setS // edgelist
> Graph;
bool hasCycle(const Graph& aG)
{
try {
std::map<Graph::vertex_descriptor, size_t> index;
auto pmap = boost::make_assoc_property_map(index);
for (auto vd : boost::make_iterator_range(boost::vertices(aG)))
index[vd] = index.size();
boost::topological_sort(
aG,
boost::make_function_output_iterator([](Graph::vertex_descriptor){}),
boost::vertex_index_map(pmap));
}
catch (boost::not_a_dag const&)
{
return true;
}
return false;
}
int main() {
}
这相当于将负担转移给来电者。这可能会(很多)有意义,具体取决于您的应用程序的性能要求。
<强> Live On Coliru 强>
#include <boost/graph/adjacency_list.hpp>
#include <boost/graph/topological_sort.hpp>
#include <boost/function_output_iterator.hpp>
typedef boost::adjacency_list<
boost::setS, // outedge list
boost::setS, // vertex list
boost::directedS, // undirected
boost::property<boost::vertex_index_t, int>, // vertex prop
boost::no_property, // edge prop
boost::no_property, // graph prop
boost::setS // edgelist
> Graph;
bool hasCycle(const Graph& aG)
{
try {
boost::topological_sort(
aG,
boost::make_function_output_iterator([](Graph::vertex_descriptor){})
);
}
catch (boost::not_a_dag const&)
{
return true;
}
return false;
}
#include <boost/graph/random.hpp>
#include <random>
int main() {
std::mt19937 prng{ std::random_device{}() };
Graph g;
boost::generate_random_graph(g, 100, 200, prng);
auto index = boost::get(boost::vertex_index, g);
int gen_id = 0;
for (auto vd : boost::make_iterator_range(boost::vertices(g))) {
boost::put(index, vd, gen_id++);
std::cout << "Vertex " << boost::get(index, vd) << "\n";
}
bool check = hasCycle(g);
}