I have a two-dimension vector like below.
vector<vector<int>> vec = {{2,5}, {3, 4}, {0,1}, {1,2}}
I want to sort this array based on the second element of each vec[i]. So the end result should be
{{2,5},{3,4},{1,2}, {0,1}}
I want to use something like
sort(vec.begin(), vec.end(), secondGreater);
bool secondGreater(vector<int> a, vector<int> b){
return a[1]>b[1];
}
My thinking is: each element of vec is a one-dimension vector, so i provide one function to compare two one-dimension vector. But somehow it doesn't work. Any hint?
Thanks.
//-------------------------------------------------
The code is like below, and the error message is
Line 6: Char 46: error: reference to non-static member function must be called sort(boxTypes.begin(), boxTypes.end(), secondGreater); ^~~~~~~~~~~~~ 1 error generated.
class Solution {
public:
int maximumUnits(vector<vector<int>>& boxTypes, int truckSize) {
int cnt=0;
sort(boxTypes.begin(), boxTypes.end(), secondGreater);
for(auto i=0;i<boxTypes.size();i++){
if(truckSize > boxTypes[i][0]){
cnt+= boxTypes[i][0] * boxTypes[i][1];
truckSize -= boxTypes[i][0];
}
else if(truckSize>0 && truckSize < boxTypes[i][0]){
cnt+= boxTypes[i][1] * truckSize;
break;
}
else break;
}
return cnt;
}
bool secondGreater(vector<int> boxA, vector<int> boxB){
return boxA[1] > boxB[1];
}
};
secondGreater
is a member function. But you are trying to call it as if it were a free function with no associated object.
Since it accesses no member variables, it doesn't need to be a member function, move it outside the class:
bool secondGreater(vector<int> boxA, vector<int> boxB){
return boxA[1] > boxB[1];
}
class Solution
If you for some reason needed it to be in the class, you could make it static:
static bool secondGreater( ...
If you need it for some reason to be a non-static member function, aka you need state from the class in the future, then you could bind
this
to it:
sort(boxTypes.begin(), boxTypes.end(), std::bind(secondGreater, this, _1, _2));
// This code is only psuedo code.
Or since it is so simple, just replace the whole thing with a lambda:
sort(boxTypes.begin(), boxTypes.end(), [](vector<int> boxA, vector<int> boxB){
return boxA[1] > boxB[1];
});