c ++排序自定义函数

The*_*own -2 c++ sorting

我需要能够传入一个变量来进行排序.我注意到它只会考虑它将要排序的类型,所以我想知道是否可以做类似的事情.

例如,我需要它按第3个int排序每个包含3个整数的数组.如果你事先不知道你将要排序的价值,你将如何制作这样的功能?

Der*_*nes 5

你说"例如,我需要它来排序每个包含3个整数的数组的第3个int",并且在运行时你不会知道哪个索引(哪个列)是重要的.

如果你能够使用C++ 11,它可以很简单:

void mysort(vector<vector<int>>& v, int col)
{
    sort(v.begin(), v.end(),
         [col](const vector<int>& a, const vector<int>& b) -> bool
               { return a[col] < b[col]; });
}
Run Code Online (Sandbox Code Playgroud)

如果你被限制在C++ 98中,你可以做同样的事情,但是你必须编写一个将列作为构造函数参数的函子来代替lambda:

class ColumnSort {
    int col_;
public:
    ColumnSort(int col): col_(col) { }
    bool operator()(const vector& a, const vector& b) const {
        return a[col_] < b[col_];
    }
};

void mysort(vector< vector<int> >& v, int col)
{
    sort(v.begin(), v.end(), ColumnSort(col));
}
Run Code Online (Sandbox Code Playgroud)

最后,如果你想要一个多列排序,那么这个仿函数就是这样的,其中cols是一个有序列的排序列表:

class ColumnSort {
    vector<int> cols_;
public:
    ColumnSort(const vector<int>& cols): cols_(cols) { }
    bool operator()(const vector<int>& a, const vector<int>& b) const {
      for (int i = 0; i < cols_.size(); ++i) {
        if (a[cols_[i]] == b[cols_[i]]) continue;
        return a[cols_[i]] < b[cols_[i]];
      }
      return false;
    }
};
Run Code Online (Sandbox Code Playgroud)