Gerard
Gerard

Reputation: 679

How to sort a 2D array using the sort function in c++?

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]]

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]]

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);
}

However, passing it to the function and compiling doesn't give an error in my source file. Instead the compiler opens up stl_algo.h and points the following error:

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

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?

Upvotes: 4

Views: 2544

Answers (1)

user529758
user529758

Reputation:

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)

This is obvious from the

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).

Upvotes: 6

Related Questions