【问题标题】:C++ - BGL: sort edgesC++ - BGL:排序边
【发布时间】:2024-04-17 02:15:02
【问题描述】:

我想知道是否有一种方法可以在不使用 lambda 函数的情况下获得提升图边缘的排序向量。

即我目前是这样排序的:

std::vector<Edge> edgs = ...;
std::sort(edgs.begin(),edgs.end(),
        [&](const Edge& e1, const Edge& e2){
            return g[e1].source < g[e2].source || (g[e1].source == g[e2].source && g[e1].target < g[e2].target);
    });

g 是我们从中获取边的图,

struct EdgeProperties{
    int weight;
    int source;
    int target;
};
typedef boost::adjacency_list<vecS,vecS,undirectedS,no_property,EdgeProperties> Graph;
typedef boost::graph_traits<Graph> Traits;
typedef Traits::vertex_descriptor Vertex;
typedef Traits::edge_descriptor Edge;

有效,但我不想使用 lambda 函数。有没有办法避免它们(仍然使用 std::sort)还是我坚持使用它们?

【问题讨论】:

  • std::sort 文档给出了不涉及 lambda 的示例。

标签: c++ sorting boost graph lambda


【解决方案1】:

您可以使用运算符和函子:

 // sort using a custom function object
    class customLess{
        Graph &_g;
    public:
        customLess(Graph g)
        {
            _g = g;
        }

        bool operator()(const Edge& e1, const Edge& e2)
        {   
           return _g[e1].source < _g[e2].source || (_g[e1].source ==  _g[e2].source && _g[e1].target < _g[e2].target);
        }   
     } ;

    std::sort(edgs.begin(), edgs.end(), customLess(g));

这样您就不必在代码中的每个排序操作中写下相同的运算符内容。

参考: http://en.cppreference.com/w/cpp/algorithm/sortC++ Functors - and their uses

【讨论】:

  • 谢谢,但是你的函数对象从哪里得到它的g?因为这就是我首先使用 lambda 函数的原因。我可以只在结构中存储对图形的引用,还是..?
  • @User1291 是的。这就是有状态函子的想法
【解决方案2】:

或者,使用默认排序比较:std::less&lt;Edge&gt;

例如:

#include <boost/tuple/tuple_comparison.hpp>

using namespace boost;

struct EdgeProperties{
    int weight;
    int source;
    int target;

private:
    auto key() const { return tie(weight, source, target); }
public:

    bool operator<(EdgeProperties const& other) const {
        return key() < other.key();
    }
};

现在

std::edge<EdgeProperties> selfsorting;

已经排序

【讨论】: