如何使用 c++ 中的排序函数对 2D 数组进行排序
How to sort a 2D array using the sort function in c++?
我有一个需要排序的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-cppmingw64libgccx86_64-w64-mingw324.7.1includec++bitsstl_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
函数参数)。
相关文章:
- 根据组件 1、2(和 3)对空间 (2D/3D) 向量进行排序
- 使用 std::sort 对 C 样式的 2D 数组进行部分排序
- 通过 std::sort 对 C 2D 数组进行排序
- 如何在不通过插入排序更改原始矢量的情况下对 2D 矢量进行排序
- 如何搜索和排序 2D 数组
- 气泡排序 2D 数组
- 2d 排序卡算法
- 2D数组排序,空格打乱顺序
- 2D 矢量排序算法
- 对通过引用传递的 2d 向量进行排序
- C 2D数组排序
- 我们如何在 c++ 中使用 std::sort 对 2D 字符串数组进行排序
- 按一行对2D数组进行排序
- 2D 字符串数组气泡排序
- 如何对主对角线上方的 2D 数组中的元素进行排序
- 仅使用 iostream 按字母顺序对 2d 数组进行气泡排序
- 根据某一行对整个 2D 向量进行排序
- C++:对2D数组进行基于1行的排序
- 根据关系的 2D 数组对数组进行排序(更高、更低、无关紧要)
- 用qsort -正确的类型转换排序2D数组