簡體   English   中英

C ++-BGL:對邊緣進行排序

[英]C++ - BGL: sort edges

我想知道是否有一種方法可以在不使用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)還是我堅持使用它們?

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

 // 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 ++函子-及其用途

或者,使用默認的排序比較: std::less<Edge>

例如:

#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;

已經排序

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM