Iterating over edges of a graph using range-based for

前端 未结 3 2122
礼貌的吻别
礼貌的吻别 2021-02-08 00:42

I have a representation of a graph as a std::vector> neighbors, that is, vertices are integers, and for each vertex we keep

3条回答
  •  逝去的感伤
    2021-02-08 01:24

    An opportunity for a shameless plug! I have a project linq-cpp for bringing .NET LINQ functionality to C++11, and this is a perfect example for where it really shines.

    Using it, you could write a function like the following:

    TEnumerable> EnumerateEdges(std::vector>& neighbors)
    {
        return Enumerable::FromRange(neighbors)
            .SelectManyIndexed([](std::unordered_set& bNodes, int aNode)
            {
                return Enumerable::FromRange(bNodes)
                    .Select([=](int bNode){ return std::make_pair(aNode, bNode); });
            });
    }
    

    And then use it like this:

    EnumerateEdges(neighbors).ForEach([](std::pair edge)
    {
        /* your code */
    });
    

    Or maybe like this:

    auto edges = EnumerateEdges(neighbors).ToVector();
    

提交回复
热议问题