【问题标题】:Multi-Key Custom Sorting in C++C++ 中的多键自定义排序
【发布时间】:2026-01-12 03:55:01
【问题描述】:

问题陈述:

我想使用我的自定义排序标准对结构的std::vector 进行排序。

结构是:

struct Node
{
   int x;
   int y;
   float value;
};

向量是:

std::vector<Node> vec;

我的自定义排序标准是矢量应首先按 y 排序,然后按 x 排序(就像在 Microsoft Excel 中一样)。

示例:

输入:

x y

5 6
2 4
1 1
1 0
8 10
4 7
7 1
5 4
6 1
1 4
3 10
7 2

输出:

x y

1 0
1 1
6 1
7 1
7 2
1 4
2 4
5 4
5 6
4 7
3 10
8 10

上述排序是否可以通过任何 C++ 标准库排序函数来实现?如果没有,我可以使用其他任何库吗?

【问题讨论】:

标签: c++ sorting vector struct


【解决方案1】:

是的,您可以使用std::sort 使用比较功能来做到这一点。

bool comparison(const Node& node1, const Node& node2)
{
    if (node1.y < node2.y) return true;
    if (node1.y == node2.y) return node1.x < node2.x;

    return false;
}

int main() {
    std::sort(vec.begin(), vec.end(), comparison);
}

【讨论】:

  • @sftrabbit:很好。谢谢!修复它
  • 我要补充一点,您可以使用任何函子(以及 C++11 lambda 函数)
  • 哇,非常感谢。我尝试使用比较器功能,但没有想到这种比较逻辑。 :)
【解决方案2】:

一般来说,当需要字典顺序时,用tie 更清楚地表示为多个字段实现比较运算符(和函数)。

static bool compare(Node const& l, Node const& r) {
    // Note the alignment so that both expressions only differ in their `l` and `r` ?
    return std::tie(l.y, l.x)
         < std::tie(r.y, r.x);
}

但是,即使这样也会留下一些重复和不一致的路径。以下助手负责:

static std::tuple<int&,int&> tuplize(Node const& n) { return std::tie(n.y, n.x); }

然后可以简单地应用:

static bool compare(Node const& l, Node const& r) {
    return tuplize(l) < tuplize(r);
}

Taaadaaam :)

【讨论】:

    【解决方案3】:

    由于C++11,你也可以使用lambda expression来代替定义比较函数:

    std::sort(std::begin(vec), std::end(vec), [](const Node& a, const Node& b) {
        return a.y < b.y || (a.y == b.y && a.x < b.x);
    });
    

    这样你可以让你的代码相当短。

    Code on Ideone

    【讨论】:

      【解决方案4】:

      std::sort 采用自定义比较函数。我没有对此进行测试,但您的可能看起来像:

      bool cmp (const Node& lhs, const Node& rhs)
      {
          if ( lhs.y < rhs.y ) return true;
          else if ( lhs.y == rhs.y ) return ( lhs.x < rhs.x );
          else return false;
      }
      

      【讨论】: