gpt4 book ai didi

C++-BGL : sort edges

转载 作者:行者123 更新时间:2023-11-30 03:48:33 32 4
gpt4 key购买 nike

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

即我目前正在这样排序:

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++ Functors - and their uses

关于C++-BGL : sort edges,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33131111/

32 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com