int main() { vector<Animal*> vec; vec.push_back(new Animal("tiger", 1.2, 250, 5)); vec.push_back(new Animal("lion", 1.0, 200, 6)); vec.push_back(new Animal("elephant", 2.5, 5000, 25)); vec.push_back(new Animal("giraffe", 5.5, 800, 12)); sort(vec.begin(), vec.end(), compareWeight); for (vector<Animal*>::iterator iter = vec.begin(); iter != vec.end(); ++iter) { cout << (*iter)->getName() << ": " << (*iter)->getWeight() << endl; } cout << "The heaviest animal: " << vec.back()->getName() << endl; for (vector<Animal*>::iterator iter = vec.begin(); iter != vec.end(); ++iter) { delete *iter; } return 0; } 这段代码不用指针应该怎么写呢?
时间: 2024-03-02 21:51:00 浏览: 97
vec.rar_VEC-326_vec482_vector 数组_容器模版Vector开发例程_数据库vec
可以使用智能指针 `std::unique_ptr` 来替代原先的裸指针,避免手动管理内存。修改后的代码如下所示:
```
int main() {
vector<std::unique_ptr<Animal>> vec;
vec.push_back(std::make_unique<Animal>("tiger", 1.2, 250, 5));
vec.push_back(std::make_unique<Animal>("lion", 1.0, 200, 6));
vec.push_back(std::make_unique<Animal>("elephant", 2.5, 5000, 25));
vec.push_back(std::make_unique<Animal>("giraffe", 5.5, 800, 12));
sort(vec.begin(), vec.end(), compareWeight);
for (auto& animal : vec) {
cout << animal->getName() << ": " << animal->getWeight() << endl;
}
cout << "The heaviest animal: " << vec.back()->getName() << endl;
return 0;
}
```
值得注意的是,在使用 `std::unique_ptr` 时,我们需要使用 `std::make_unique` 来分配内存。此外,由于智能指针会自动管理内存,我们不再需要手动删除指针,因此删除指针的那个循环可以省略。
阅读全文