CodeGuru Home VC++ / MFC / C++ .NET / C# Visual Basic VB Forums Developer.com
Results 1 to 3 of 3
  1. #1
    Join Date
    Mar 2008
    Posts
    70

    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

  2. #2
    Join Date
    Apr 1999
    Posts
    27,449

    Re: how could i do this??

    Quote 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

  3. #3
    Join Date
    Nov 2006
    Location
    Essen, Germany
    Posts
    1,344

    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
  •  





Click Here to Expand Forum to Full Width

Featured