C++ C++;-BGL:对边进行排序

C++ C++;-BGL:对边进行排序,c++,sorting,boost,graph,lambda,C++,Sorting,Boost,Graph,Lambda,我想知道是否有一种方法可以在不使用lambda函数的情况下获得boost图边的排序向量 也就是说,我目前的排序方式如下: 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].s

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

也就是说,我目前的排序方式如下:

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);
    });

可以,但我不想使用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));
//使用自定义函数对象进行排序
类自定义{
图形和图形;
公众:
自定义(图g)
{
_g=g;
}
布尔运算符()(常数边和e1、常数边和e2)
{   
返回_g[e1]。源<_g[e2]。源| |(_g[e1]。源==_g[e2]。源&&&u g[e1]。目标<_g[e2]。目标);
}   
} ;
std::sort(edgs.begin()、edgs.end()、customLess(g));
这样您就不必在代码中的每个排序操作中都写下相同的运算符内容

参考: 和

或者,使用默认排序比较:
std::less

例如:

#包括
使用名称空间boost;
结构边属性{
整数权重;
int源;
int目标;
私人:
auto key()常量{return tie(权重、源、目标);}
公众:

bool运算符该文档提供了不涉及lambda的示例。谢谢,但是您的函数对象从哪里获得其
g
?因为这就是我首先使用lambda函数的原因。我可以只在结构中存储对图形的引用吗?或者..@User1291是的。这就是有状态函子的概念
 // 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));
#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;