为什么我不能将类的对象插入到多集?



我创建了一个Animal类,然后创建了一个普通函数,该函数接受两个Animal对象,并使用<运算符比较它们在集合中的排序。multiset的声明没有给出错误,但是当我试图将Animal类的对象插入到multiset时,它给出了错误。你能告诉我如何插入物体吗?代码一直编译到最后一行,在这一行中对象被插入到multiset中。你能告诉我怎么做吗?>

class Animal{
public:
Animal(std::string, std::string, int);
std::vector<std::string> achievements;
int getAge()const {return age;};
private:
std::string name;
std::string kind;
int age;
};
Animal::Animal(std::string n, std::string k, int a): name(n), kind(k), age(a){};
bool compareAge(Animal &a, Animal &b){
return a.getAge() < b.getAge();
}
int main(){
Animal firstAnimal("Dog", "Mammal", 4);
Animal secondAnimal("Pigeon", "Bird", 1);
std::multiset<Animal, decltype(compareAge)*>animalSet(compareAge);
animalSet.insert({firstAnimal, secondAnimal});
std::multiset<Animal, decltype(compareAge)*>animalSet(compareAge);

关联容器中的键总是const。这是因为一旦一个值被插入到关联容器中,它的键就不能改变,因此它必须是constant。

bool compareAge(Animal &a, Animal &b){
return a.getAge() < b.getAge();
}
不幸的是,这个比较器接受对一对可变对象的引用。然而,由于上面解释的原因,关联容器只能将对const对象的引用传递给比较器,并且在c++中不能将对const对象的引用转换为对非const对象的引用。这应该是:
bool compareAge(const Animal &a, const Animal &b){
return a.getAge() < b.getAge();
}

在c++中,这条经验法则永远不会出错:如果一个函数不应该修改它的形参,那么形参应该是const

最新更新