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

    Multiple sort options in C++

    Hi

    I have the following private part of a class defined as follows:

    private:
    struct stats {
    double ISIsum;
    int authorCount;
    bool operator<(const stats &a) const { return ISIsum > a.ISIsum;}
    } *stats_;

    bool compareSortByISI(const stats &lhs, const stats &rhs);

    };


    This enables me to sort this struct by calling:

    std::sort(stats_, stats_ + authors_->getMaximumAuthors());

    My question is, what if I want to have the option to sort by authorCount or ISIsum at run time. Is there any way to do this?

    I can't see how I can override operator< twice and decide which one to call at use time.

    Thx

    G

  2. #2
    Join Date
    Jul 2005
    Location
    Netherlands
    Posts
    2,042

    Re: Multiple sort options in C++

    Quote Originally Posted by gxkendall View Post
    My question is, what if I want to have the option to sort by authorCount or ISIsum at run time. Is there any way to do this?

    I can't see how I can override operator< twice and decide which one to call at use time.
    Look at the documentation for std::sort.
    There are two overloads and the second takes a comparator that is used instead of operator <.
    So, you can simply implement two functions that compare either authorCount or ISIsum and then use one or the other based on other information.
    Cheers, D Drmmr

    Please put [code][/code] tags around your code to preserve indentation and make it more readable.

    As long as man ascribes to himself what is merely a posibility, he will not work for the attainment of it. - P. D. Ouspensky

  3. #3
    Join Date
    Sep 2006
    Posts
    13

    Re: Multiple sort options in C++

    Excellent - took a bit of working out, but up and running.

    Many thanks.

    G

Tags for this Thread

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