2015-10-14 63 views
1

我想知道是否有一种方法来获得升压图边的排序向量,而不使用lambda函数。C++ - BGL:排序边

I.e.我目前的排序是这样的:

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)还是我坚持使用它们?

+1

['std :: sort'](http://en.cppreference.com/w/cpp/algorithm/sort)文档给出了不涉及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

+0

谢谢,但是你的函数对象从哪里得到''g''?因为这就是我首先使用lambda函数的原因。我可以只在结构中存储对图形的引用,或者..? – User1291

+1

@ User1291是的。这就是有状态函子的概念 – sehe

1

可替代地,使用默认排序比较: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; 

已经排序