改变相邻顶点的值并移除自循环
Change value of adjacent vertices and remove self loop
尝试用boost::graph编写一个更大的算法
示例(第一列为顶点,其他为相邻顶点):
- 1 2 3
- 2 1 3 4
- 3 1 2 4
- 3
假设我将2和1合并,我得到结果
- 1 2 3 2 1 1 3 4
- 2 1 3 4
- 3 1 2 4
- 3
第一个问题:我如何改变顶点1的相邻顶点("2"到"1")?
my naive solution
template<typename Vertex, typename Graph>
void change_adjacent_vertices_value(Vertex input, Vertex value, Graph &g)
{
for (auto it = boost::adjacent_vertices(input, g);
it.first != it.second; ++it.first){
if(*it.first == value){
*(it.first) = input; //error C2106: '=' : left operand must be l-value
}
}
}
显然,我不能通过这种方式将相邻顶点的值设置为1
在"change_adjacent_vertices_value"之后我想要的结果
- 1 1 3 1 1 1 4
- 2 1 3 4
- 3 1 2 4
- 3
第二个问题:我怎样才能弹出相邻的顶点?
假设我想从顶点1中弹出连续的1我所期望的结果
- 1 1 3 1 3 4
- 2 1 3 4
- 3 1 2 4
- 3
任何函数像"pop_adjacent_vertex"可以使用?
首先,在大多数情况下,图顶点描述符只是一个整数或指针。这意味着代码中的赋值不会改变图形。
相反,你应该使用来自可变图概念的API: http://www.boost.org/doc/libs/1_55_0/libs/graph/doc/MutableGraph.html
在你的例子中,代码看起来像:
///adds all edges from src to target and removes the vertex src from the graph
template<typename Vertex, typename Graph>
void merge_vertices(Vertex src, Vertex tgt, Graph &g)
{
for (auto it = boost::out_edges(src, g);
it.first != it.second; ++it.first)
{
Vertex u = target(*it.first,g);
add_edge(u,tgt,g);
//Note, if edges have properties, you should extract and copy them as well
}
clear_vertex(src,g); //removes all edges to/from "src"
remove_vertex(src,g); //removes vertex src itself
}
为了避免混淆,我建议在删除边或顶点时使用顶点和边描述符不会失效的图。
它导致以下测试示例:
typedef boost::adjacency_list<boost::listS,
boost::listS, boost::undirectedS > graph_t;
typedef boost::graph_traits<graph_t>::vertex_descriptor vertex_t;
int main(int, char**)
{
typedef std::map<vertex_t, size_t> IndexMap;
IndexMap mapIndex;
graph_t g;
vertex_t v0 = add_vertex(g);
mapIndex[v0]=0;
vertex_t v1 = add_vertex(g);
mapIndex[v1]=1;
vertex_t v2 = add_vertex(g);
mapIndex[v2]=2;
vertex_t v3 = add_vertex(g);
mapIndex[v3]=3;
add_edge(v0,v2,g);
add_edge(v1,v3,g);
add_edge(v1,v0,g);
std::cout << "Before merging " << std::endl;
boost::print_graph(g, boost::make_assoc_property_map(mapIndex));
merge_vertices(v1,v2,g);
std::cout << "After merging "<< std::endl;
boost::print_graph(g, boost::make_assoc_property_map(mapIndex));;
}
结果:Before merging
0 <--> 2 1
1 <--> 3 0
2 <--> 0
3 <--> 1
After merging
0 <--> 2 2
2 <--> 0 3 0
3 <--> 2
相关文章:
- 如何循环打印顶点结构
- 如何在C++中从两个单独的for循环中添加两个数组
- C++我的数学有什么问题,为什么我的代码不能正确循环
- 正在尝试了解输入验证循环
- std::map<struct,struct>::find 找不到匹配项,但是如果我循环通过 begin() 到 end(),我在那里看到匹配项
- 循环后如何继续阅读
- Ardunio UNO解决了多个重叠的定时器循环
- Eigen如何在容器循环中干净地附加矩阵
- 在某些循环内使用vector.push_back时出现分段错误
- 我正在使用嵌套的while循环来解析具有多行的文本文件,但由于某种原因,它只通过第一行,我不知道为什么
- 为什么我的for循环不能正确获取argv
- 如何声明特征矩阵,然后通过嵌套循环初始化它
- while循环中while循环的时间复杂度是多少
- C++中的高效循环缓冲区,它将被传递给C样式数组函数参数
- 似乎无法使用<VERTEX>迭代器在 for 循环中打印列表顶点?C++
- 循环以将顶点保存在openGL中
- BGL:是否可以使用C++11的范围在图的顶点上循环
- 如果图中只有一个循环,如何找到无向图中哪些顶点是循环的
- 内在循环依赖C++顶点和向量
- 改变相邻顶点的值并移除自循环