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

    What happens when comparator has a return value of 0?

    Code:
      private static final Comparator<Node> comparator = new Comparator<Node>() {
            public int compare(Node one, Node two) {
                if (one.id == two.id)
                    return 0;
                if (one.f < two.f)
                    return -1;
                if (one.f > two.f)
                    return 1;
                return (one.id < two.id) ? -1 : 1;
            }
        };
    Could anyone please explain each branch, how each element would be arranged in each case?
    For example, when one.id == two.id, it returns 0; will "one" be put after or before "two"?
    Thanks
    Jack

  2. #2
    Join Date
    May 2006
    Location
    UK
    Posts
    4,473

    Re: What happens when comparator has a return value of 0?

    Read the API docs for the method.

    how each element would be arranged in each case?
    For example, when one.id == two.id, it returns 0; will "one" be put after or before "two"?
    This method just returns a numeric value depending on whether one object is greater than, equal to, or less than the other. The method doesn't know about object order nor does it change the order of any objects, that is down to the calling object (assuming it wants to impose some sort of ordering).

    For example: If you have a class that wants to order a collection of objects in descending order and it calls this method repeatedly to ascertain the order, the following would happen. If the method returns < 0 then object 1 will be placed after object 2. If the return value is 0 most implementations would not change the order of the objects but there is no rule which says they can't. And if it returns > 0 object 1 will be placed before object 2.
    Posting code? Use code tags like this: [code]...Your code here...[/code]
    Click here for examples of Java Code

  3. #3
    Join Date
    Dec 2010
    Posts
    907

    Re: What happens when comparator has a return value of 0?

    I'd like to port this to C++
    I don't know you are a C++ programmer or not, but is the following correct
    Code:
    struct Comparator
    {
        bool operator() (const Node *a, const Node *b)
        {
                if (a->id == b->id)
                   return false;
               if (a->f  < b->f)
                   return true;
               if (a->f > b->f)
                  return false;
                return (a->id < b->id) ? false : true;
    
     
             
    
        }
    };
    is this correct?
    Last edited by lucky6969b; March 2nd, 2012 at 09:41 AM.

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