【问题标题】:How to use sort() in C++ with custom sort member function?如何在 C++ 中通过自定义排序成员函数使用 sort()?
【发布时间】:2023-03-12 12:17:01
【问题描述】:

我有一个关于将比较函数传递给sort() 的问题。

我想要做的是定义一个sort() 函数,该函数在计算时考虑到我要在其中进行排序的类的成员变量。

基本上,我的代码如下所示(简化为仅显示相关部分):

MappingTechnique.h

struct MappingTechnique {
    vector<int> usedIndexCount; 
};

struct SimpleGreedyMappingTechnique : MappingTechnique {
    bool sortByWeights(int index1, int index2);
};

MappingTechnique.m

bool SimpleGreedyMappingTechnique::sortByWeights(int index1, int index2) {
    return usedIndexCount[index1] > usedIndexCount[index2];
}

void SimpleGreedyMappingTechnique::processFrame(Frame frame) {
    vector<int> payloadIndices = <generate the vector>

    // sort the payload indices according to their current usedIndexCount
    sort(payloadIndices.begin(), payloadIndices.end(), sortByWeights);
}

此代码无法编译,它给出以下错误:

 error: reference to non-static member function must be called

并指向sortByWeights

甚至可以使用类的成员函数进行排序吗?如果是,我该如何实现?

【问题讨论】:

    标签: c++ sorting functor


    【解决方案1】:

    是的,但总的来说,我鼓励只使用适当的仿函数或 lambda:

    使用 lambda:

    std::sort(payloadIndices.begin(), payloadIndices.end(), [this](int a, int b){
        return this->sortByWeights(a, b);
    });
    

    或者使用std::mem_fn:

    auto sorter = std::bind(std::mem_fn(SimpleGreedyMappingTechnique::sortByWeights), this);
    std::sort(payloadIndices.begin(), payloadIndices.end(), sorter);
    

    或者使用仿函数:

    namespace{
    struct indicies_less_than
    {
        const SimpleGreedyMappingTechnique & mapping_tech;
        indicies_less_than(const SimpleGreedyMappingTechnique & mapping_tech)
           :mapping_tech(mapping_tech){}
    
        bool operator()(int a, int b)
        {
           return mapping_tech.sortByWeights(a, b);
        }
    };
    }
    
    std::sort(payloadIndices.begin(), payloadIndices.end(), indicies_less_than(*this));
    

    注意:

    如果要排序的类型比int 更复杂,您肯定希望通过const&amp; 传递它们以防止复制

    【讨论】:

    • 我考虑过使用 lambda 函数,但我是 c++ 新手,所以我真的不知道如何在这里应用它...您的回答很有帮助,再次感谢!跨度>
    • 正如原发帖人遇到的,根据编译器的不同,std::sort不能使用成员函数,所以一个functor(函数运算符,上面没有给出的例子),一个lambda函数,或者上面显示的第二个示例将起作用。仿函数早于 lambda[] 和其他方法,因此对于较旧的编译器,您可能需要使用仿函数。
    【解决方案2】:

    正如 Mgetz 所提到的,可以使用仿函数。函子示例:

    #include <algorithm>
    #include <cstdlib>
    #include <iostream>
    #include <iomanip>
    #include <vector>
    
    #define asize 16
    
    class example{
    public:
        unsigned int a[asize];      // array
        std::vector<size_t> v;      // indices to array
    
    example(void)
    {
        v.resize(asize);
        for(size_t i = 0; i < asize; i++){
            a[i] = rand()%10;
            v[i] = i;
        }
    }
    
    void displayarray(void)
    {
        for(size_t i = 0; i < asize; i++)
            std::cout << std::setw(3) << a[v[i]];
        std::cout << std::endl;
    }
    
    class lessthan                  // lessthan functor for std::sort
    {
    public:
    const example &x;
        lessthan(const example &e ) : x(e) { }
        bool operator()(const size_t & i0, const size_t & i1)
        {
            return x.a[i0] < x.a[i1];
        }
    };
    
    void sortarray(void)
    {
        std::sort(v.begin(), v.end(), lessthan(*this));
    }
    };
    
    int main()
    {
    example x;
    
        x.displayarray();
        x.sortarray();
        x.displayarray();
        return 0;
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2012-04-09
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多