leon
leon

Reputation: 181

Different ways of using a comparator in C++

I saw two different answers in Leetcode using comparators:

  1. why is the first Comp function defined outside of the class? Even when I bring Comp into the class, the Leetcode fails.

  2. How are you able to use Comp with out the ()?

  3. How come I often see compare in structs?

bool Comp(const string& a, const string& b) {
    ...
}

class Solution {
public:
    vector<string> reorderLogFiles(vector<string>& logs) {
        stable_sort(logs.begin(), logs.end(), Comp);
        // ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~^ here
        return logs;
    }
};

and then

struct CompareLogs
{
    bool operator() (const string& str1, const string& str2)
    {
        ...
    }
};

vector<string> reorderLogFiles(vector<string>& logs) {
    sort(letter_logs.begin(), letter_logs.end(), CompareLogs());
    // ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~^ and here       
    return letter_logs;
}

Upvotes: 0

Views: 95

Answers (1)

Victor
Victor

Reputation: 470

why is the first Comp function defined outside of the class?

As long as your self-defined function fulfills the expected parameters, you can place it inside or outside the class.

Even when I bring Comp into the class, the Leetcode fails.

You need to add static to make it class-independent:

class Solution
{
public:

    static bool Comp(const std::string& a, const std::string& b)
    {
    }

    std::vector<std::string> reorderLogFiles(std::vector<std::string>& logs)
    {
        std::stable_sort(logs.begin(), logs.end(), Comp);
        return logs;
    }
};

How come I often see compare in structs?

I do not see any advantage here.

Finally, one advice: use std:: prefix, do not omit it. You will avoid future problems.

Upvotes: 1

Related Questions