Reputation: 169
I was writing a program where I had to use custom sort, so I made a custom comparator "comp", but using it inside C++ class, gives "reference to non-static member function must be called", I fixed this using static bool comp(). But after making my comparator functions static, I am getting the error "invalid use of member 'mat' in static member function". How do I get through these?
I have called sort(str.begin(), str.end(), comp()), and from "comp", I haved called "comp_()". I had to sort the string in a different manner.
class Solution {
public:
int mat[26][26];
static bool comp_(char a, char b, int i) {
if (i == 26) {
return a<b;
}
if (mat[a-'A'][i] > mat[b-'A'][i]) {
return true;
}
else if (mat[a-'A'][i] < mat[b-'A'][i]) {
return false;
}
return comp_(a,b,i+1);
}
static bool comp(char a, char b) {
return comp_(a,b,0);
}
Upvotes: 0
Views: 1099
Reputation: 73091
The trick is to define a call-operator on your Solution
class so that it can be used as a Comparator object that is passed to the std::sort()
call, like this:
#include <iostream>
#include <vector>
using namespace std;
class Solution {
public:
int mat[26][26];
bool comp(char a, char b, int i) const {
if (i == 26) {
return a<b;
}
if (mat[a-'A'][i] > mat[b-'A'][i]) {
return true;
}
else if (mat[a-'A'][i] < mat[b-'A'][i]) {
return false;
}
return comp(a,b,i+1);
}
bool operator()(const char & a, const char & b) const
{
return comp(a, b, 0);
}
};
int main(int argc, char ** argv)
{
std::vector<char> str;
str.push_back('d');
str.push_back('c');
str.push_back('b');
str.push_back('a');
Solution sol;
std::sort(str.begin(), str.end(), sol);
for (size_t i=0; i<str.size(); i++) std::cout << str[i] << std::endl;
return 0;
}
That way the methods in your Solution
object do not have to be static, and therefore they can access the mat
member variable.
Upvotes: 1