|
-
March 6th, 2008, 07:14 PM
#1
how could i do this??
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
-
March 6th, 2008, 07:22 PM
#2
Re: how could i do this??
 Originally Posted by ALEXSNIPER
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
-
March 7th, 2008, 03:41 AM
#3
Re: how could i do this??
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).
Code:
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.
Code:
#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).
Last edited by GNiewerth; March 7th, 2008 at 03:46 AM.
- Guido
Posting Permissions
- You may not post new threads
- You may not post replies
- You may not post attachments
- You may not edit your posts
-
Forum Rules
|
Click Here to Expand Forum to Full Width
|