Binary predicate help

Im a little confuse on binary predicate

If i got a code like this

1
2
3
4
5
6
7
8
 bool Generic_algorithm::isShort(string &s1, string &s2){
	return s1.size() < s2.size();
}

int main(){
vector<string>words{"hi","hello","hey"};
	 stable_sort(words.begin(), words.end(), isShort);
}


How does the predicate isShort gets its argument?
If isShort gets its argument on vector words then it only accounts to the first parameter. How about the second parameter?

Where does it gets the second paramter?

if is look like this when called
isShort("hi",?); then what is the question mark? what is its second argument?

Where does it compare the "hi"?

I am learning lambda. And it kinda uses predicate style format.
Last edited on
How does the predicate isShort gets its argument?

stable_sort is passed a function pointer to isShord stable_sort uses this function pointer to call isShort with the appropriate arguments.

If isShort gets its argument on vector words then it only accounts to the first parameter

i'm not sure what you mean the third parameter to stable_sort expects a function pointer to a function with two parameters and therefore knows it needs to pass two arguments.

Where does it compare the "hi"?

well I would assume there is some code inside stable_sort that exits the function if there is only one object because a single object cant be sorted.

Last edited on
The function is called by a sorting algorithm. Sorting changes the order of elements in a sequence, if they are not in the desired order already. Therefore, the sort must test two -- not just one -- values in order to know whether they have to be reordered.

It is up to the implementation of the stable_sort, when it calls the predicate and with what.
i'm not sure what you mean the third parameter to stable_sort expects a function pointer to a function with two parameters and therefore knows it needs to pass two arguments.


Third function calls a pointer to that function and it knows it needs two arguments to pass. Then what does it pass?

I mean when stable_sort calls the isShort. Then ti should pass a two arguments like this

isShort(words[0],words[1]);

and not just isShort right?

So does it mean that it is passing the vector it self? Or does it pass string one by one?

Its a little confusing to me because of the second argument.
So does it mean that it is passing the vector it self? Or does it pass string one by one?

It passes two strings at the same time not the vector
stable_sort is an comparison sort. See http://en.wikipedia.org/wiki/Comparison_sort

What each of those does compare is up to them. For example, the quicksort compares a pivot value to other elements within range.
Thanks guys i got it now
Topic archived. No new replies allowed.