c++ - 如何使用 C++ 中的排序函数对二维数组进行排序?

标签 c++ arrays sorting

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

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

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

[[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>'

是标准排序函数不兼容这种类型的输入,还是有其他问题。如果不兼容,是否有解决此问题的解决方法?

最佳答案

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

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 函数参数)。

关于c++ - 如何使用 C++ 中的排序函数对二维数组进行排序?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21179413/

相关文章:

c++ - 构造函数中的段错误,但仅限于某些模板参数

arrays - 如何指定返回的数组类型?

java - 需要帮助解释该程序的结果

java - 我使用数组编译 java 彩票程序时出现 2 个错误

php - 在 PHP 中对数组进行双重排序

c++ - 通过指向其基址的指针删除 POD 对象是否安全?

c++ - 删除这些指针时出错

C++ - 无法通过构造函数初始化类变量

mysql单表SELECT查询ORDER BY导致FILESORT

javascript - 对 MemoryStore(或任意数据数组)中的数据进行排序