如何使用c ++中的sort函数对2D数组进行排序?

时间:2014-01-17 06:38:16

标签: c++ arrays sorting

我有一个n x m数组,我需要排序。但是,我只需要查看每个1d数组的第一个值来对较大的数组进行排序。例如,考虑以下2d数组:

[[1, 2], [4, 4], [3, 5]]

我不关心子阵列中的第二个值。我只需要查看子数组的第一个值来对其进行排序。所以,我只会看1, 4, 3。排序,我得到:1, 3, 4。但是整个2d数组看起来应该是这样的:

[[1, 2], [3, 5], [4, 4]]

我尝试使用标准排序算法在c ++中实现它:

#include <vector>
#include <algorithm>

using namespace std;

bool compare(vector<int>& a, vector<int>& b) {
    return a[0] < b[0];
}

int main() {
    vector< vector<int> > a(3);
    //The array I'm building is already sorted. I'm just using it as a test. 
    for (int i = 0; i < 3; i++) {
        vector<int> temp(2, 0);
        temp[0] = i;
        a.push_back(temp);  
    }
    sort(a.begin(), a.end(), compare);
}

但是,将其传递给函数并进行编译不会在源文件中出错。而是编译器打开stl_algo.h并指出以下错误:

2289 4 c:\program files (x86)\dev-cpp\mingw64\lib\gcc\x86_64-w64-mingw32\4.7.1\include\c++\bits\stl_algo.h [Error] invalid initialization of reference of type 'std::vector<int>&' from expression of type 'const std::vector<int>'

标准排序功能是否与此类输入不兼容,还是存在其他问题。如果它不兼容,可以解决这个问题吗?

1 个答案:

答案 0 :(得分:6)

由于比较器函数不应该修改它们的参数,你必须以接受const引用的方式创建比较器:

bool compare(const vector<int> &a, const vector<int>& b)

中可以明显看出这一点
invalid initialization of reference of type 'std::vector<int>&' from expression of type 'const std::vector<int>

错误消息的一部分(您无法将const对象传递给非const函数参数。)