对的任何替代方案?

问题描述 投票:2回答:5

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

c++ c functional-programming
5个回答
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; });

5
投票
struct vertex
{
int x;
int y;
};

然后相应地排序结构。


2
投票

您可以使用struct指出并在其他答案中显示。但是,如果您定义自己的结构,则需要定义比较器函数以与排序算法一起使用或重载<运算符。

使用std::pair的优点是你不需要定义一个比较器,因为std::pair重载运算符<,先按第一个元素排序,然后按第二个元素排序。有关示例,请参阅此answer


0
投票

最好的方法是@Gopi作为答案的结构。对于字典排序,您可以使用std :: tie(http://en.cppreference.com/w/cpp/utility/tuple/tie)。

struct vertex
{
    int x;
    int y;
    bool less_x(const struct vertex& b) const { return std::tie(x,y) < std::tie(b.x, b.y); }
    bool less_y(const struct vertex& b) const { return std::tie(y,x) < std::tie(b.y, b.x); }
};

0
投票
int c = x*n + y    where, n>x and n>y 

x=c/n 
y=c%n

当你需要x时,只需c/n将给xy使用c%n给y。

注意:仅适用于正坐标

© www.soinside.com 2019 - 2024. All rights reserved.