Click to See Complete Forum and Search --> : how could i do this??


ALEXSNIPER
March 6th, 2008, 06:14 PM
i have this struct
struct StudentRec
{
int age;
string name;
int id;
};
and two overloaded functions
void Sort(StudentRec student[].id); //here the problem
void Sort(StudentRec student[].age); //here too

how can i write two overloaded Functions and pass specific field from struct

Paul McKenzie
March 6th, 2008, 06:22 PM
i have this struct
struct StudentRec
{
int age;
string name;
int id;
};
and two overloaded functions
void Sort(StudentRec student[].id); //here the problem
void Sort(StudentRec student[].age); //here too
You can't solve a problem by using invalid syntax.

Functions are overloaded based on type, not variable name. Both of those variables, age and id are ints. Therefore you can't overload on them, because they are the same type.

Please explain exactly what you're trying to really accomplish.

Regards,

Paul McKenzie

GNiewerth
March 7th, 2008, 02:41 AM
You need to provide two different functions to sort an array of student objects by two different attributes. Please notice that you have to pass the length of the array, too, because when passing an array it decays to a simple pointer without additional information. The most simple way is to provide two different comparison functions, depending on the member you want to sort by. Most sort() implementations (donīt know which one you are using) take a pointer to a comparison function (or something similar).


bool compare_by_id( const StudentRec& op1, const StudentRec& op2 )
{
return op1.id < op2.id;
}

bool compare_by_age( const StudentRec& op1, const StudentRec& op2 )
{
return op1.age < op2.age;
}


Now you can use one of these functions to sort the array by age and id.


#include <algorithm>

int main()
{
StudentRec Students[500];

std::sort( Students, Students +500, compare_by_id );
std::sort( Students, Students +500, compare_by_age );
}


If you donīt know how to use std::sort please look it up, itīs part of the Standard Template Library (STL).