对的任何替代方案?

Any alternative for pairs?

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

struct vertex
{
int x;
int y;
};

然后相应地对结构进行排序。

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

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

您可以使用 std::pair<int, int> 存储这对坐标,或者如@Gopi 的答案所示 struct

可以使用 lambda 函数、仿函数或全局函数按 X 坐标或 Y 坐标对其中任何一个的集合进行排序。

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

最好的方法是 struct 作为@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); }
};
int c = x*n + y    where, n>x and n>y 

x=c/n 
y=c%n

当您需要 x 时,只需 c/n 即可得到 x,对于 y,使用 c%n 即可得到 y。

注意:仅适用于正坐标