user6490375 - 1 year ago 70
C++ Question

# Evaluation of the binary predicates in C++

How are the binary predicates evaluated?

For example, if I want to sort in the descending order, then should I write:

bool isGreater(int x, int y)
{
return x > y;
}

or

bool isGreater(int x, int y)
{
return y > x;
}

What exactly is the difference between the two? I understand that the two parameters would be compared to each other, but what should the return result be -
true
or
false
? And how does it matter? So, my question basically is, how do I determine if the first argument should go before the second one, if I don't know the order in which they will be passed?

The
sort()
function would be called in this fashion (
height
is the array to be sorted):

sort(height, height+N, isGreater);

Note: I did refer links like this one and this one, but they don't explicitly focus on this problem.

Could someone please clarify my doubt? Thanks!

Here is a very simple ascending order sorting algorithm in psuedo code:

for i ← 1 to length(A)-1
j ← i
while j > 0 and A[j-1] > A[j]
swap A[j] and A[j-1]
j ← j - 1
end while
end for

Same thing with a predicate "MyCompare(x, y) { return x <= y; }" looks like this:

for i ← 1 to length(A)-1
j ← i
while j > 0 and MyCompare(A[j-1], A[j]) == false
swap A[j] and A[j-1]
j ← j - 1
end while
end for

Now the sort algorithm can sort in any order just by changing the predicate. Since this predicate is an argument to std::sort that means std::sort can sort in any order.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download