写一个c++类,管理不同结构体的数据,要求 1.提供将结构体数据序例化为map存储在此类中 2.提供将类中的数据通过结构体的名称读取数据
时间: 2024-06-08 22:10:09 浏览: 186
以下是一个简单的实现,供参考:
```c++
#include <iostream>
#include <map>
#include <string>
#include <vector>
using namespace std;
struct Student {
string name;
int age;
string major;
};
struct Teacher {
string name;
int age;
string subject;
};
class DataManager {
public:
void addStudent(const Student& s) {
//将学生结构体序列化为map,并添加到数据管理类中
map<string, string> data;
data["name"] = s.name;
data["age"] = to_string(s.age);
data["major"] = s.major;
m_studentData.push_back(data);
}
void addTeacher(const Teacher& t) {
//将教师结构体序列化为map,并添加到数据管理类中
map<string, string> data;
data["name"] = t.name;
data["age"] = to_string(t.age);
data["subject"] = t.subject;
m_teacherData.push_back(data);
}
string getStudentData(int index, const string& field) {
//根据索引和字段名获取学生数据
if (index >= m_studentData.size()) {
return "";
}
map<string, string> data = m_studentData[index];
if (data.count(field) == 0) {
return "";
}
return data[field];
}
string getTeacherData(int index, const string& field) {
//根据索引和字段名获取教师数据
if (index >= m_teacherData.size()) {
return "";
}
map<string, string> data = m_teacherData[index];
if (data.count(field) == 0) {
return "";
}
return data[field];
}
private:
vector<map<string, string>> m_studentData;
vector<map<string, string>> m_teacherData;
};
int main() {
DataManager dm;
Student s1 = {"Tom", 18, "Computer Science"};
Student s2 = {"Lily", 19, "Mathematics"};
Teacher t1 = {"John", 35, "History"};
Teacher t2 = {"Mary", 40, "Literature"};
dm.addStudent(s1);
dm.addStudent(s2);
dm.addTeacher(t1);
dm.addTeacher(t2);
cout << dm.getStudentData(0, "name") << endl; //输出 "Tom"
cout << dm.getStudentData(1, "major") << endl; //输出 "Mathematics"
cout << dm.getTeacherData(0, "age") << endl; //输出 "35"
cout << dm.getTeacherData(1, "subject") << endl; //输出 "Literature"
return 0;
}
```
阅读全文