C++ 读取文本文件内容到结构体数组中并排序
作者::2024-03-06 21:07:18 C++阅读 3135
C++ 读取文本文件内容到结构体数组中并排序
C++ 读取文本文件内容到结构体数组中并排序
以下是一个C++程序示例,它演示了如何读取文本文件的内容到结构体数组中,并对结构体数组进行排序。在这个示例中,假设文本文件中的每一行包含姓名和年龄,以空格分隔。
#include <iostream>
#include <fstream>
#include <string>
#include <vector>
#include <algorithm>
using namespace std;
// 定义一个结构体表示一个人的信息
struct Person {
string name;
int age;
};
// 比较函数,用于排序
bool comparePeople(const Person& p1, const Person& p2) {
return p1.age < p2.age;
}
int main() {
// 打开文件
ifstream file("people.txt");
if (!file) {
cerr << "无法打开文件!" << endl;
return 1;
}
// 创建一个存储人员信息的vector
vector<Person> people;
string name;
int age;
// 从文件中读取每一行,并将其解析为姓名和年龄,存储到结构体数组中
while (file >> name >> age) {
Person person{name, age};
people.push_back(person);
}
// 关闭文件
file.close();
// 对人员信息按年龄进行排序
sort(people.begin(), people.end(), comparePeople);
// 打印排序后的人员信息
cout << "按年龄从小到大排序后的人员信息:" << endl;
for (const auto& person : people) {
cout << "姓名: " << person.name << ", 年龄: " << person.age << endl;
}
return 0;
}野牛程序员教少儿编程与信息学奥赛-微信|电话:15892516892

