对的任何替代方案?

Man*_*kar 2 c c++ functional-programming

我有很多点(a,b),我将x坐标存储在b []的[]和y坐标中.现在我需要用x坐标或y坐标对这些点进行排序.我知道C++中存在对的概念,但有没有更好的方法来做到这一点.请用C/C++给出答案.

R S*_*ahu 6

您可以使用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)


Gop*_*opi 5

struct vertex
{
int x;
int y;
};
Run Code Online (Sandbox Code Playgroud)

然后相应地排序结构.

  • @ user3901994`std :: sort(std :: begin(an_array),std :: end(an_array),[](vertex const&a,vertex const&b){return ax <bx;});`< - 用`ay <by`替换`ax <bx`,用`y`字段而不是`x`字段排序. (2认同)
  • @cdhowie我认为有助于指出你的隔离专区使用lambda函数并需要编译C++ 11标志. (2认同)