I am solving a problem on LeetCode to make a pair sort and give the output basically link - https://leetcode.com/problems/the-k-weakest-rows-in-a-matrix/
this is my code
class Solution {
public:
bool sortbysec(const pair<int,int> &a,
const pair<int,int> &b)
{
if(a.first == b.first)
return (a.second < b.second);
return (a.first > b.first);
}
vector<int> kWeakestRows(vector<vector<int>>& mat, int k) {
vector<pair<int,int>>zeros;
vector<int>res;
for(int i = 0;i<mat.size();i++){
zeros.push_back(make_pair(count(mat[i].begin(),mat[i].end(),0),i)) ;
}
sort(zeros.begin(),zeros.end(),sortbysec);
int n = zeros.size();
for(int i = 0;i<mat.size();++i){
res.push_back(zeros[i].second);
}
return res;
}
};
i get this error 1st time and don't know about it what to do to solve it
You cannot pass a non-static member function to std::sort
in that way because it would need an instance of Solution
to call it on.
Fortunately, the solution in this case is simple: since sortbysec
doesn't reference any member variables, you can declare it static
:
static bool sortbysec(const pair<int,int> &a,
const pair<int,int> &b)
If you do need to call a non-static member function as your sort function, you can do it via a capturing lambda:
sort(zeros.begin(),zeros.end(),
[this] (const pair<int,int> &a, const pair<int,int> &b)
{ return sortbysec (a, b); });
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.