【问题标题】:How to sort a 2D array using the sort function in c++?如何使用 C++ 中的排序函数对二维数组进行排序?
【发布时间】:2014-01-17 06:38:16
【问题描述】:

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

[[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&lt;int&gt;&amp;' from expression of type 'const std::vector&lt;int&gt;'

是标准排序功能与这种类型的输入不兼容,还是有其他问题。如果不兼容,有没有办法解决这个问题?

【问题讨论】:

  • 由于比较器函数不应该修改它们的参数,因此您必须创建比较器以便它接受 const 引用:bool compare(const vector&lt;int&gt; &amp;a, const vector&lt;int&gt;&amp; b)。从错误消息中可以明显看出这一点。
  • @H2CO3:把这个写成答案怎么样?
  • @ChristianSeverin 完成,谢谢。

标签: c++ arrays sorting


【解决方案1】:

由于比较器函数不应该修改其参数,因此您必须以接受 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 函数参数)。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-04-14
    • 2013-12-16
    • 2021-11-07
    • 1970-01-01
    • 1970-01-01
    • 2023-03-10
    • 2013-09-13
    • 2019-05-17
    相关资源
    最近更新 更多