在保持相对顺序的同时对向量的向量进行排序

时间:2020-09-29 00:44:36

标签: c++ sorting vector

我一直在尝试实现一个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];
});

1 个答案:

答案 0 :(得分:1)

只需使用std::stable_sort并提供条件以进行排序:

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

以降序排列[first,last)范围内的元素。 保证等效元素的顺序得到保留

强调是我的