如何排序使用排序功能在C ++中二维数组? [英] How to sort a 2D array using the sort function in c++?

查看:291
本文介绍了如何排序使用排序功能在C ++中二维数组?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个 n×m的数组,我需要排序。不过,我只需要看看每个维数组的第一个值较大数组进行排序。例如,请考虑下面的二维数组:

I have an n x m array that I need sorted. However, I only need to look at the first value of each 1d array to sort the larger array. For example, consider the following 2d array:

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

我不关心子阵第二个值。我只需要看看子数组的第一个值来排序。所以,我只会看 1,4,3 。排序它,我得到: 1,3,4 。但整个二维数组应该是这样的:

I don't care about the second values in the subarrays. I just need to look at the first value of subarray to sort it. So, I would only look at 1, 4, 3. Sorting it, I get: 1, 3, 4. But the whole 2d array should look like:

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

我试着在C与标准的排序算法执行这一++:

I tried implementing this in c++ with the standard sort algorithm:

#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 \\包括\\ C ++ \\位\\ stl_algo.h [错误]类型的引用无效初始化的std ::矢量&lt;&INT GT;&放大器;'从类型的前pression'矢&lt常量的std ::; INT&GT;

是标准的排序功能不适用于这种类型的输入兼容,或者是有一些其他的问题。如果它不兼容,可就是没有解决此问题的方法?

Is the standard sort function not compatible with this type of input, or is there some other problem. If it's not compatible, can is there a workaround to solve this problem?

推荐答案

由于比较函数不应该修改其参数,你必须以这样的方式来创建你比较它接受常量引用:

Since comparator functions aren't supposed to modify their arguments, you have to create your comparator in such a way that it accepts const references:

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>

该错误消息的一部分(你可以不通过常量对象非 - 常量函数的参数)。

part of the error message (you can't pass a const object to a non-const function argument).

这篇关于如何排序使用排序功能在C ++中二维数组?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆