C++ 在C++;

C++ 在C++;,c++,struct,boolean,comparator,C++,Struct,Boolean,Comparator,我在使用比较器的Leetcode中看到了两个不同的答案: 为什么第一个Comp函数是在类之外定义的?即使我把Comp带到类中,Leetcode也会失败 您如何在不使用()的情况下使用Comp 为什么我经常在结构中看到比较 bool Comp(常量字符串和a、常量字符串和b){ ... } 类解决方案{ 公众: 矢量重新排序日志文件(矢量和日志){ 稳定排序(logs.begin()、logs.end()、Comp); //在这里 返回日志; } }; 然后 struct CompareL

我在使用比较器的Leetcode中看到了两个不同的答案:

  • 为什么第一个
    Comp
    函数是在类之外定义的?即使我把
    Comp
    带到类中,Leetcode也会失败

  • 您如何在不使用
    ()
    的情况下使用
    Comp

  • 为什么我经常在结构中看到比较

  • bool Comp(常量字符串和a、常量字符串和b){
    ...
    }
    类解决方案{
    公众:
    矢量重新排序日志文件(矢量和日志){
    稳定排序(logs.begin()、logs.end()、Comp);
    //在这里
    返回日志;
    }
    };
    
    然后

    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;
    }
    
    struct CompareLogs
    {
    布尔运算符()(常量字符串和str1、常量字符串和str2)
    {
    ...
    }
    };
    矢量重新排序日志文件(矢量和日志){
    排序(letter_logs.begin()、letter_logs.end()、CompareLogs());
    //在这里
    回信记录;
    }
    
    为什么在类之外定义第一个Comp函数

    只要自定义函数满足预期参数,就可以将其放置在类内部或外部

    即使我把Comp带到课堂上,Leetcode也会失败

    您需要添加
    static
    ,使其独立于类:

    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;
        }
    };
    
    类解决方案
    {
    公众:
    静态bool Comp(常数std::string&a,常数std::string&b)
    {
    }
    std::vector reorderLogFiles(std::vector和日志)
    {
    std::stable_sort(logs.begin()、logs.end()、Comp);
    返回日志;
    }
    };
    
    为什么我经常在结构中看到比较

    我看不出这有什么好处


    最后,有一条建议:使用
    std::
    前缀,不要忽略它。您将避免将来出现问题。

    您可能希望了解函数指针和functor类(也称为方法)中的非静态函数有一个隐式参数
    ,该参数允许它访问类成员。这使它不同于常规函数。你不能混合和匹配函数和方法,它们只是不同而已。@Alan,我看了函子。所以结构比较器是一个函子。考虑的首要方案是什么?当必须在多个调用之间携带状态信息时,通常使用函数指针函子。在现代C++中,A可以代替ScReNeNOS。非捕获lambda类似于独立函数,而捕获lambda类似于函子。
    
    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;
        }
    };