在C++98中,可以使用std::list模板类来创建一个存储结构体指针的列表,并且为该列表提供增删改查的接口函数。以下是一个示例,展示了如何定义结构体、创建结构体指针的std::list以及实现增删改查的接口函数:
#include <iostream>
#include <list>
#include <string>
// 定义结构体
struct Person {
std::string name;
int age;
Person(const std::string& n, int a) : name(n), age(a) {}
};
// 使用结构体指针的list
class PersonList {
private:
std::list<Person*> list;
public:
// 析构函数,释放所有内存
~PersonList() {
for (Person* p : list) {
delete p;
}
}
// 添加元素
void add(const std::string& name, int age) {
Person* newPerson = new Person(name, age);
list.push_back(newPerson);
}
// 删除元素(按名字)
bool remove(const std::string& name) {
for (std::list<Person*>::iterator it = list.begin(); it != list.end(); ++it) {
if ((*it)->name == name) {
delete *it; // 释放内存
list.erase(it); // 从list中删除元素
return true;
}
}
return false;
}
// 修改元素(按名字)
bool update(const std::string& name, int newAge) {
for (Person* p : list) {
if (p->name == name) {
p->age = newAge;
return true;
}
}
return false;
}
// 查找元素(按名字)
Person* find(const std::string& name) {
for (Person* p : list) {
if (p->name == name) {
return p;
}
}
return nullptr;
}
// 打印所有元素
void printAll() {
for (Person* p : list) {
std::cout << "Name: " << p->name << ", Age: " << p->age << std::endl;
}
}
};
int main() {
PersonList people;
// 添加元素
people.add("Alice", 25);
people.add("Bob", 30);
// 打印所有元素
people.printAll();
// 修改元素
people.update("Alice", 26);
// 再次打印所有元素
people.printAll();
// 删除元素
people.remove("Bob");
// 再次打印所有元素
people.printAll();
// 查找元素
Person* foundPerson = people.find("Alice");
if (foundPerson) {
std::cout << "Found Alice: " << foundPerson->name << ", " << foundPerson->age << std::endl;
} else {
std::cout << "Alice not found." << std::endl;
}
return 0;
}
在这个例子中,PersonList类管理了一个std::list<Person*>,它存储了指向Person结构体的指针。PersonList类提供了以下方法:
add: 向列表中添加一个新的Person对象。
remove: 根据名字从列表中删除一个Person对象,并释放其内存。
update: 根据名字修改列表中一个Person对象的年龄。
find: 根据名字查找列表中一个Person对象,并返回指向它的指针。
printAll: 打印列表中所有Person对象的信息。
注意,在PersonList的析构函数中遍历整个列表并删除每个Person对象,以确保不会造成内存泄漏。
在main函数中,我们展示了如何使用PersonList类来添加、修改、删除和查找Person对象。这个简单的例子展示了如何在C++98中使用结构体指针和std::list。
1410

被折叠的 条评论
为什么被折叠?



