传递类方法而不是 std::sort 中的函数

发布于 2024-09-01 10:15:21 字数 1412 浏览 2 评论 0原文

在一个类中,我试图通过传递同一类的方法来对向量进行排序。但是编译的时候会报错。谁能告诉我问题是什么吗?谢谢你!

它给出以下错误: bool (Sorter::)(D&, D&)' 类型的参数不匹配bool (Sorter::*)(D&, D&)'

我也尝试过使用 sortBynumber(D const&d1,D const&d2)

#include<vector>
#include<stdio.h>
#include<iostream>
#include<algorithm>

class D {
      public:                   
             int getNumber();            
             D(int val);
             ~D(){};
      private:
              int num;
};

D::D(int val){
         num = val;
         };

int D::getNumber(){
    return num;
};


class Sorter {
      public:                   
             void doSorting();  
             bool sortByNumber(D& d1, D& d2);
             std::vector<D> vec_D;          
             Sorter();
             ~Sorter(){};
      private:
              int num;
};

Sorter::Sorter(){                 
        int i;
        for ( i = 0; i < 10; i++){
            vec_D.push_back(D(i));
           }
         };

bool Sorter::sortByNumber(D& d1, D& d2){
     return d1.getNumber() < d2.getNumber();
     };

void Sorter::doSorting(){
     std::sort(vec_D.begin(), vec_D.end(), this->sortByNumber);
     };




int main(){    
    Sorter s;
    s.doSorting();

    std::cout << "\nPress RETURN to continue...";
    std::cin.get();

    return 0;
}

Within a class, I am trying to sort a vector, by passing a method of the same class. But it gives errors at the time of compilation. Can anyone tell what the problem is? Thank you!

it gives the following error:
argument of type bool (Sorter::)(D&, D&)' does not matchbool (Sorter::*)(D&, D&)'

I have also tried using sortBynumber(D const& d1, D const& d2)

#include<vector>
#include<stdio.h>
#include<iostream>
#include<algorithm>

class D {
      public:                   
             int getNumber();            
             D(int val);
             ~D(){};
      private:
              int num;
};

D::D(int val){
         num = val;
         };

int D::getNumber(){
    return num;
};


class Sorter {
      public:                   
             void doSorting();  
             bool sortByNumber(D& d1, D& d2);
             std::vector<D> vec_D;          
             Sorter();
             ~Sorter(){};
      private:
              int num;
};

Sorter::Sorter(){                 
        int i;
        for ( i = 0; i < 10; i++){
            vec_D.push_back(D(i));
           }
         };

bool Sorter::sortByNumber(D& d1, D& d2){
     return d1.getNumber() < d2.getNumber();
     };

void Sorter::doSorting(){
     std::sort(vec_D.begin(), vec_D.end(), this->sortByNumber);
     };




int main(){    
    Sorter s;
    s.doSorting();

    std::cout << "\nPress RETURN to continue...";
    std::cin.get();

    return 0;
}

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(4

夏末 2024-09-08 10:15:21

使 Sorter::sortByNumber 静态。由于它不引用任何对象成员,因此您无需更改任何其他内容。

class Sorter {
public:                   
    static bool sortByNumber(const D& d1, const D& d2);
    ...
};

// Note out-of-class definition does not repeat static
bool Sorter::sortByNumber(const D& d1, const D& d2)
{
    ...
}

您还应该使用 const 引用,因为 sortByNumber 不应修改对象。

Make Sorter::sortByNumber static. Since it doesn't reference any object members, you won't need to change anything else.

class Sorter {
public:                   
    static bool sortByNumber(const D& d1, const D& d2);
    ...
};

// Note out-of-class definition does not repeat static
bool Sorter::sortByNumber(const D& d1, const D& d2)
{
    ...
}

You should also use const references as sortByNumber should not be modifying the objects.

不奢求什么 2024-09-08 10:15:21

除非您有充分的理由不这样做,否则只需为您要排序的项目类型定义 operator< ,然后完成它:

class D { 
    int val;
public:
    D(int init) : val(init) {}
    bool operator<(D const &other) { return val < other.val; }
};

class sorter { 
    std::vector<D> vec_D;
public:
    void doSorting() { std::sort(vec_d.begin(), vec_D.end()); }
};

您编写 sorter< 的方式/code> 类依赖于对 D 类的内部了解很多,以至于它们实际上是一个类(例如,看起来两者都不能做任何事都离不开对方)。

据猜测,您的排序器可能是真实代码的精简版本。 SortByNumber 听起来原始代码可能支持多种不同类型的键,例如:

class D { 
    std::string name;
    int height;
    int weight;
// ...
};

并且您希望能够按名称对 D 对象进行排序、身高或体重。在这种情况下,比较实际上仍然与 D 类相关,因此我可能会将它们放入公共命名空间中:

namespace D { 
class D { 
    std::string name;
    int height;
    int weight;
public:
    friend class byWeight;
    friend class byHeight;
    friend class byName;
    // ...
};

struct byWeight { 
   bool operator()(D const &a, D const &b) { 
       return a.weight < b.weight;
   }
};

struct byHeight {
    bool operator()(D const &a, D const &b) { 
        return a.height < b.height;
    }
};

struct byName { 
    bool operator()(D const &a, D const &b) { 
        return a.name < b.name;
    }
};
}

然后排序看起来像这样:

std::vector<D::D> vec_D;

// sort by height:
std::sort(vec_D.begin(), vec_D.end(), D::byHeight());

// sort by weight:
std::sort(vec_D.begin(), vec_D.end(), D::byWeight());

// sort by name:
std::sort(vec_D.begin(), vec_D.end(), D::byName());

请注意,这确实不使用免费函数。对于这种目的,函子通常是更可取的。我还使用命名空间来显示正在排序的对象与不同的排序方式之间的关联。您可以将它们改为嵌套类,但我通常更喜欢公共名称空间(保持耦合尽可能松散合理)。

无论如何,如果可以避免的话,我不会通过对象的公共接口访问原始数据(甚至是只读访问)(在本例中,可以避免)。

Unless you have a really good reason to do otherwise, just define operator< for the type of items you're sorting, and be done with it:

class D { 
    int val;
public:
    D(int init) : val(init) {}
    bool operator<(D const &other) { return val < other.val; }
};

class sorter { 
    std::vector<D> vec_D;
public:
    void doSorting() { std::sort(vec_d.begin(), vec_D.end()); }
};

The way you're writing your sorter class depends on knowing a lot about the internals of the D class, to the point that they're practically a single class (e.g., it looks like neither can do much of anything without the other).

At a guess, your sorter may be a somewhat stripped-down version of your real code. The SortByNumber makes it sound like the original code might support a number of different kinds of keys, something like:

class D { 
    std::string name;
    int height;
    int weight;
// ...
};

and you'd want to be able to sort D objects by name, height, or weight. In a case like that, the comparisons are really still related to the D class, so I'd probably put them into a common namespace:

namespace D { 
class D { 
    std::string name;
    int height;
    int weight;
public:
    friend class byWeight;
    friend class byHeight;
    friend class byName;
    // ...
};

struct byWeight { 
   bool operator()(D const &a, D const &b) { 
       return a.weight < b.weight;
   }
};

struct byHeight {
    bool operator()(D const &a, D const &b) { 
        return a.height < b.height;
    }
};

struct byName { 
    bool operator()(D const &a, D const &b) { 
        return a.name < b.name;
    }
};
}

Then sorting would look something like:

std::vector<D::D> vec_D;

// sort by height:
std::sort(vec_D.begin(), vec_D.end(), D::byHeight());

// sort by weight:
std::sort(vec_D.begin(), vec_D.end(), D::byWeight());

// sort by name:
std::sort(vec_D.begin(), vec_D.end(), D::byName());

Note that this does not use free functions. For this kind of purpose, a functor is generally preferable. I've also used a namespace to show the association between the object being sorted and the different ways of sorting it. You could make them nested classes instead, but I'd generally prefer the common namespace (keep coupling as loose as reasonable).

In any case, I would not give access to the raw data (even read-only access) via the object's public interface if it could be avoided (and in this case, it can be).

木槿暧夏七纪年 2024-09-08 10:15:21

我认为 sortByNumber() 没有理由成为成员函数。当它是成员函数时,它可以访问它不需要的东西(因此不应该访问)。要么提取方法并将其重构为函数对象:

struct sortByNumber {
    bool operator()(const D& d1, const D& d2) const {
        return d1.getNumber() < d2.getNumber();
    }
};

要么使其成为自由函数。如果可以选择,您应该更喜欢函数对象,因为这使得编译器可以在选择时内联代码。然后,您可以像这样排序:

std::sort(vec_D.begin(), vec_D.end(), sortByNumber());

也就是说,您可以使用 boost::bind() 来编译代码:

std::sort(vec_D.begin(), vec_D.end(),
          boost::bind(&Sorter::sortByNumber, this, _1, _2));

您将需要 boost 库才能工作,并且您将需要#include

I see no reason for sortByNumber() to be a member function. When it's a member function it gains access to things it doesn't need (and therefore shouldn't have access to). Either extract the method and refactor it into a function object:

struct sortByNumber {
    bool operator()(const D& d1, const D& d2) const {
        return d1.getNumber() < d2.getNumber();
    }
};

or make it a free function. Given the choice you should prefer a function object, because that makes it possible for the compiler to inline the code if it so chooses. Then, you can sort like so:

std::sort(vec_D.begin(), vec_D.end(), sortByNumber());

That said, you can get the code to compile as is like so, with boost::bind():

std::sort(vec_D.begin(), vec_D.end(),
          boost::bind(&Sorter::sortByNumber, this, _1, _2));

You will need the boost libraries for that to work, and you will need to #include <boost/bind.hpp>.

演出会有结束 2024-09-08 10:15:21

我不认为有任何理由将 sortByNumber 作为 Sorter 类的成员函数。如果将其设为自由函数,则可以更轻松地进行排序,避免所有丑陋的绑定代码。此外,只要代码中适用,您就应该使用 const。以下是使用 free 函数执行此操作的示例:

首先将 int getNumber() 更改为 const 函数,如 int getNumber() const;

然后编写您的 free 函数 sortByNumber 再次通过 const 引用获取参数。
bool sortByNumber(const D& d1, const D& d2);

您可以将 sort 调用为:
std::sort(vec_D.begin(), vec_D.end(), sortByNumber);

I don't see any reason to make sortByNumber as a member function of class Sorter. You can do the sorting much more easily avoiding all the ugly bind code if you make it a free function. Also, you should use const wherever it is applicable in the code. Following is the example of doing it using free function:

First change the int getNumber() to const function as int getNumber() const;

Then write your free function sortByNumber again taking parameters by const reference.
bool sortByNumber(const D& d1, const D& d2);

You can call sort as :
std::sort(vec_D.begin(), vec_D.end(), sortByNumber);

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文