Man*_*kar 2 c c++ functional-programming
我有很多点(a,b),我将x坐标存储在b []的[]和y坐标中.现在我需要用x坐标或y坐标对这些点进行排序.我知道C++中存在对的概念,但有没有更好的方法来做到这一点.请用C/C++给出答案.
您可以使用std::pair<int, int>@Gopi指示的方式存储坐标对,或者作为答案struct.
其中任何一个的集合都可以通过X坐标或Y坐标使用lambda函数,仿函数或全局函数进行排序.
// A vector of vertices.
std::vector<std::pair<int, int>> vertices;
// Sort the vertices by X coordinates using a lambda function to order them
std::sort(vertices.begin(), vertices.end(),
[](auto const& a, auto const& b) { return a.first < b.first; });
// Sort the vertices by Y coordinates using a lambda function to order them
std::sort(vertices.begin(), vertices.end(),
[](auto const& a, auto const& b) { return a.second < b.second; });
Run Code Online (Sandbox Code Playgroud)
struct vertex
{
int x;
int y;
};
Run Code Online (Sandbox Code Playgroud)
然后相应地排序结构.