首页 > 解决方案 > 在保持相对顺序的同时对向量进行排序

问题描述

我一直在尝试实现一个 c++ 程序,该程序按升序对向量向量进行排序,同时在出现平局的情况下保持当前顺序(例如,如果向量 a 在向量 b 之前,则 a 在 b 之前)。这是我现在拥有的代码。任何提示将不胜感激!

编辑:顺便说一句, c 是您排序的列

sort(v.begin(), v.end(), [=] (vector<int> &a, vector<int> &b) {
      if (a[c] == b[c]) {
            int d1 = find(v.begin(), v.end(), a)-v.begin();
            int d2 = find(v.begin(), v.end(), b)-v.begin();
            return d1 < d2;
      }
      return a[c] < b[c];
});

标签: c++sortingvector

解决方案


只需使用std::stable_sort并提供标准进行排序:

std::stable_sort(v.begin(), v.end(), [=] (vector<int> &a, vector<int> &b) {
      return a[c] < b[c];
});

以非降序对范围 [first, last) 中的元素进行排序。保证保持等价元素的顺序

重点是我的


推荐阅读