CodeGuru Home VC++ / MFC / C++ .NET / C# Visual Basic VB Forums Developer.com
Results 1 to 11 of 11

Threaded View

  1. #8
    Lindley is offline Elite Member Power Poster
    Join Date
    Oct 2007
    Location
    Seattle, WA
    Posts
    10,895

    Re: Sorting for equal_range()

    Quote Originally Posted by gulHK View Post
    can write this "bool operator<(const MyPred& p) const" overloaded method out side of struct
    Yes, operators can be defined either as members or non-members. In many cases it makes no difference.

    actually that's what I need, the overloaded operator consists of variables that should have the same values in order for any two elements of the vector to be considered equal
    Take care----there are two different but related concepts at work: equality, and equivalence.

    To have equality, you will need an operator== or equivalent function.
    To have equivalence, you only need that (A < B) is false, and (B < A) is also false. Note that here < can be replaced by any function defining a strict weak ordering.

    Both equal_range() and sort() only care about equivalence.

    is it possible to write more than one comparison method with different comparison criteria?
    Certainly, that's exactly what was done just up-thread. However, you can have only one operator< for a type, so any alternative comparison criteria will need to be defined as named functions or functors, or lambdas. For readability, it's generally best not to have an operator< at all when there are going to be multiple types of comparison done, so there is no confusion about which sorting order is being used at any given time.

    The only thing you have to do is make sure that the same comparator (comparison function/functor/lambda) is passed to both sort() and equal_range(). (Or one which at least imposes the same order.)
    Last edited by Lindley; January 19th, 2012 at 04:53 PM.

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