Binary predicate help

Jul 27, 2014 at 11:51am
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 Jul 27, 2014 at 11:53am
Jul 27, 2014 at 12:05pm
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 Jul 27, 2014 at 12:08pm
Jul 27, 2014 at 12:11pm
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.
Jul 27, 2014 at 12:17pm
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.
Jul 27, 2014 at 12:20pm
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
Jul 27, 2014 at 2:30pm
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.
Jul 28, 2014 at 8:55am
Thanks guys i got it now
Topic archived. No new replies allowed.