How do I sort a string using a custom compare function in C ++?

I need to sort the characters of a string and have lower letters first. For example, after sorting, "acDbA" becomes "abcAD".

Below is the code:

bool compare(const char& c1, const char& c2) {
    if (c1 >= 'A' && c1 <= 'Z' && c2 >= 'a' && c2 <= 'z') return false;
    if (c2 >= 'A' && c2 <= 'Z' && c1 >= 'a' && c1 <= 'z') return true;
    return c1<c2;
}
void sortLetters(string &letters) {
    sort(letters.begin(), letters.end(), compare);
}

      

However, in Visual Studio I got:

'sort': no matching overloaded function found   
'SortLetters::compare': non-standard syntax; use '&' to create a pointer to member  
'void std::sort(_RanIt,_RanIt)': expects 2 arguments - 3 provided   

      

How to create a custom comparison function to sort a string, I couldn't find examples on the internet with sorting strings.

+3


source to share


2 answers


The above code just compiles when using a free function. In your case, you are using an object method that is not just being called.



You can pass a functor object or a lambda object. By the way, since std :: sort is a function template, it doesn't matter what the exact parameters of the comparator are. The only thing that matters is that it can take both values ​​and return something that can be converted to bool.

+2


source


The code below works, only change - the compare item function is now marked as "static":



class SortLetters {
public:
    static bool compare(const char& c1, const char& c2) {
        if (c1 >= 'A' && c1 <= 'Z' && c2 >= 'a' && c2 <= 'z') return false;
        if (c2 >= 'A' && c2 <= 'Z' && c1 >= 'a' && c1 <= 'z') return true;
        return c1<c2;
    }
    void sortLetters(string &letters) {
        sort(letters.begin(), letters.end(), compare);
    }
};

      

+1


source







All Articles