如何按结构的成员对文件中的数据进行排序?C++

How do I sort data from file by member of a struct? C++

本文关键字:排序 数据 C++ 文件 结构 何按 成员      更新时间:2023-10-16

这里我有一个程序,它从文件中读取一些员工数据,并将它们存储在结构数组中。我试图使用"sort_by_age"函数来根据出生日期对数据进行排序,从最年长的员工到最年轻的员工。"read_file"函数运行良好,程序编译良好,但输出不正确,程序没有按照我的意愿对数据进行正确排序。如有任何帮助,我们将不胜感激。

以下是文件中的几行内容,介绍的格式

114680858 19670607 Matilda Vincent MI
114930037 19471024 Desdemona Hanover ID
115550206 19790110 Xanadu Perlman ND
116520629 19630921 Alexander Hall SD

例如,如果这是文件中的所有行(不是),我希望它先对Desdemona的信息进行排序,然后是alexander的信息,然后是matilda的信息,再是xanadu的信息。

#include<string>
#include<iostream>
#include<fstream>
using namespace std;
struct employees // employee data
{
int ss_number;//social security
int dob;//date of birth YYYY/MM/DD Ex.) 19870314=1987/03/14
string f_name;
string l_name;
string state; //state of residence };

void read_file()//read file into array of 1000 structs
{
ifstream data("/home/www/class/een118/labs/database1.txt");
employees array[100]
if(!data.fail())
{
int i;
for(int i=0;i<100;i++)
{
data>>array[i].ss_number
>>array[i].dob
>>array[i].f_name
>>array[i].l_name
>>array[i].state;
}
for(int i=0;i<100;i++)
{
cout<<array[i].ss_number>>" "<<array[i].dob>>" "<<array[i].f_name>>" "<<
array[i].l_name>>" "<<array[i].state;
}}}

void print_person(employees e)
{
cout<<e.ss_number>>" "<<e.dob>>" "<<e.f_name>>" "<<e.l_name>>" "<<e.state;
}
void sort_by_age(employees array[])
{
employees temp;
for(int i=0;i<100;i++)
{
for(int j=i+1;j<100;j++)
{
if(array[j].dob<array[i].dob)
{
temp=array[i];
array[i]=array[j];
array[j]=temp;}
print_person(array[j]);
cout<<"n";}}}


int main()
{
employees array[100];
read_file(array);
sort_by_age(array);
}

使用std::sort,例如最好使用lambda。

#include <string>
#include <iostream>
#include <fstream>
#include <algorithm>
using namespace std;
struct employee {
   int social_security_id;
   int date_of_birth;
   string first_name;
   string last_name;
   string state;
};
// parses and returns a vector of employees from the given stream.
std::vector<employee> parse_employees(ifstream ifs)
{
   std::string str;
   std::vector<employee> v;
   while (!ifs.eof()) {
      employee e;
      ifs >> e.social_security_id >> e.date_of_birth >> e.first_name >> e.last_name >> e.state;
      v.push_back(e);
   }
   return v;
}
int main(int argc, char* argv[])
{
   ifstream ifs("/home/www/class/een118/labs/database1.txt");
   auto employees = parse_employees(ifs);
   std::sort( std::begin(employees), std::end(employees),
      []( const employees &a, const employees &b )
      {
         return ( a.date_of_birth > b.date_of_birth );
      });
   for (auto e : v) {
      cout << e.social_security_id << e.date_of_birth << e.first_name << e.last_name << endl;
   }
}