ZBLOG

#include #include #include using namespace std; class Person { public: Person() {} Person(string name,int age) { this->m_name = name; this->m_age = age; } string m_name; int m_age; }; class Mycmp { public: bool ope...

这是因为你在使用自定义比较函数对象Mycmp时,将其声明为了常量对象。由于set容器默认使用严格弱排序(strict weak ordering)的比较方式,要求比较函数是const成员函数。

解决这个问题的方法是将operator()函数声明为const成员函数:

bool operator()(const Person &person1, const Person &person2) const {
    return person1.m_age < person2.m_age;
}

通过添加const关键字,在函数后面表示该成员函数不会修改任何类成员变量的值,从而使得它能够与常量对象一起使用。

修改后的代码如下:

#include<iostream>
#include<set>
#include<string>
using namespace std;

class Person {
public:
    Person() {}
    Person(string name, int age) {
        this->m_name = name;
        this->m_age = age;
    }
    string m_name;
    int m_age;
};

class Mycmp {
public:
    bool operator()(const Person& person1, const Person& person2) const {
        return person1.m_age < person2.m_age;
    }
};

int main() {
    Person p1("小明", 18);
    Person p2("kevin", 21);
    Person p3("tom", 16);
    Person p4("shirol", 26);
    Person p5("kesen",22);

    set<Person, Mycmp> s;
    
	s.insert(p1);
	s.insert(p2);
	s.insert(p3);
	s.insert(p4);
	s.insert(p5);

	for (auto it = s.begin(); it != s.end(); it++) {
		cout << "姓名:" << (*it).m_name << "  年龄:" << (*it).m_age << " ";
	}
	cout << endl;

	return 0;
}

现在,你应该能够正常编译和运行这段代码,并且按照年龄升序打印出Person对象的信息。


内容由零声教学AI助手提供,问题来源于学员提问

本站部分文章来源于网络,版权归原作者所有,如有侵权请联系站长删除。
转载请注明出处:https://golang.0voice.com/?id=13329

分享:
扫描分享到社交APP
上一篇
下一篇
发表列表
游客 游客
此处应有掌声~
评论列表

还没有评论,快来说点什么吧~

联系我们

在线咨询: 点击这里给我发消息

微信号:3007537140

上班时间: 10:30-22:30

关注我们
x

注册

已经有帐号?