#include <iostream> #include <vector> #include <algorithm> using namespace std; class Animal { public: Animal(string _name, double _height, double _weight, int _age) : name(_name), height(_height), weight(_weight), age(_age) {} string name; double height; double weight; int age; }; bool cmp(const Animal &a, const Animal &b) { return a.weight < b.weight; } int main() { vector<Animal*> vec; vec.push_back(new Animal("Elephant", 2.5, 5000, 20)); vec.push_back(new Animal("Giraffe", 5.5, 800, 10)); vec.push_back(new Animal("Lion", 1.2, 250, 8)); vec.push_back(new Animal("Panda", 1.0, 150, 6)); sort(vec.begin(), vec.end(), cmp); double maxWeight = 0; Animal* maxWeightAnimal = nullptr; for (auto animal : vec) { cout << "Animal name: " << animal->name << ", weight: " << animal->weight << endl; if (animal->weight > maxWeight) { maxWeight = animal->weight; maxWeightAnimal = animal; } } if (maxWeightAnimal) { cout << "The heaviest animal is " << maxWeightAnimal->name << ", weight: " << maxWeightAnimal->weight << endl; } for (auto animal : vec) { delete animal; } return 0; }这段代码的输出结果是什么?
时间: 2024-03-01 16:56:32 浏览: 67
#include_iostream.h_
4星 · 用户满意度95%
这段代码的输出结果为:
```
Animal name: Panda, weight: 150
Animal name: Lion, weight: 250
Animal name: Elephant, weight: 5000
Animal name: Giraffe, weight: 800
The heaviest animal is Elephant, weight: 5000
```
首先,代码创建了一个 Animal 类,并定义了一个比较函数 cmp,用于按照动物体重升序排序。然后,代码创建了一个 vector,向其中添加了四个动物实例。接着,代码使用 sort 函数按照动物体重进行排序,并输出每个动物的名称和体重。然后,代码找到最重的动物,并输出其名称和体重。最后,代码释放动物实例的内存。
阅读全文