如何将此程序中的员工数据从最年长的人排序为最年轻的人?C++

How Do I Sort The Employee Data In This Program From Oldest Person To Youngest Person? C++

本文关键字:排序 C++ 最年长 数据 程序      更新时间:2023-10-16

这里有一个程序,它将一个员工数据文件读取到一个结构数组中。我有一个函数,可以搜索数组,找到最年长的人,并打印出那个人的数据。但现在我需要修改一个函数,该函数对数组进行排序,并将最年长的人的数据移动到数组中的第一个位置,将第二年长的人移动到第二个位置,依此类推,并对所有1000名员工进行同样的操作,以便它将从最年长到最年轻对所有员工数据进行排序并打印。我怎么能这么做?

以下是给出布局概念的前几行数据(出生日期为YYYYMMDD

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

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[1000]
if(!data.fail())
{
int i;
for(int i=0;i<1000;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<1000;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 find_oldest(employees array[])// oldest person = smallest dob
{
int i;
int index=0
int oldest=1000000000;//dummy variable
for(i=1;i<1000;i++)//1000 is array length
{
if(array[i].dob<oldest)
{
index=i;
oldest=array[i].dob;
}
}
print_person(array[i]);
}

int main()
{
employees array[1000];
read_file(array);
find_oldest(array);
}

不清楚为什么函数被调用为find_oldest。

然而,您可以使用标准算法std::sort和一个可以是lambda表达式的比较函数。例如

#include <iostream>
void find_oldest( employees array[], size_t n )
{
   std::sort( array, array + n, 
              []( const employees &e1, const employees &e2 )
              {
                 return ( e1.dob > e2.dob );
              } );  
   for ( size_t i = 0; i < n; i++ ) print_person( array[i] );
}

另一种不使用lambda表达式的方法是为结构雇员或函数对象声明operator >。在我看来,最好定义一个函数对象。在这种情况下,对于任何类型的排序,例如按名字或姓氏排序,都可以使用单独的函数对象。例如

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 
   struct sort_by_dob
   {
      bool operator ()( const employees &e1, const employees &e2 ) const
      {
         return ( e1.dob > e2.dob );
      }
   };
};

void find_oldest( employees array[], size_t n )
{
   std::sort( array, array + n, employees::sort_by_dob() );  
   for ( size_t i = 0; i < n; i++ ) print_person( array[i] );
}

编写一个自定义比较函子/函数/运算符并将其传递给std::sort():

bool operator<( const employees& lhs , const employees& rhs )
{
    return std::tie( lhs.f_name , lhs.l_name ) < std::tie( rhs.f_name , rhs.l_name );
}
int main()
{
    std::vector<employees> database; //Or an array, its the same.
    std::sort( std::begin( database ) , std::end( database ) );
}