c++ passing a function into a function???

Status
Not open for further replies.

daKarateKid

Seniorius Lurkius
8
I am teaching myself C++ using 'Accelerated C++' by Andrew Koenig and Barbara E. Moo. In the past, I have taught myself some rudimentary Java, have had a semester of C, and can hack VB well enough. This book is great so far, but I have one unresolved question in the six chapters that I have studied.

While working with the vector container, the book presents a problem when sorting structs. The book points out that the sort() function can take an optional 3rd argument which is a predicate defining how to sort the vector of structs. So far so good. That 3rd argument is a predicate which is defined by a function (compare) that tells the program to sort based off of Student_info.name.

Student_info.h
code:<HR>
Code:
struct Student_info {
	std::string name;
	double midterm, final;
	std::vector<double> homework;
};
bool compare(const Student_info&, const Student_info&);

Student_info.cc
code:<HR>
Code:
bool compare(const Student_info& x, const Student_info& y)
{
	return x.name < y.name;
}

grades.cc
code:<HR>
Code:
int main(){
	vector<Student_info> students;
	// do some other stuff
	sort(students.begin(), students.end(), compare)
	//do more stuff
}

My question is why is it that the arguments for compare are not passed into sort()? The program compiles correctly. I haven't been able to verify that it runs as it should, however. Intuitively, I would have guessed that the sort function should have been written as:

code:<HR>
Code:
sort(students.begin(), students.end(), compare(students.begin(), students.end())

Why is this not necessary? Is it ever necessary, or allowable to do it the way I've outlined? Thanks.
 
Your compare() function is generic. Give it two arguments, and it returns which one is larger, smaller, or whatever. So the sort() generic algorithm is going to call it whenever it needs a comparison between any two elements. Calling compare( students.begin(), students/end() ) on the other hand would only compare the first and last element of your sequence - not exactly what you want, I am sure.

PO
 

daKarateKid

Seniorius Lurkius
8
Calling compare( students.begin(), students/end() ) on the other hand would only compare the first and last element of your sequence - not exactly what you want, I am sure.

You're right, this wouldn't be desirable.

What does it mean to be generic in this context? Is it something to do with the fact that the inner function will use every iteration of the arguments provided by the outer functions? Does it mean that the inner function must have exactly the same number and type of arguments as the outer function?
 

sorghumking

Ars Scholae Palatinae
989
Passing a function into a function is a perfectly legal (and extremely useful) thing to do in C++. Check the index of your book for "function pointers" or "pointers to functions" and see what you find, it should clear things up a bit. If that yields nothing, check out "The C Programming Language" (Kernighan & Ritchie) or "The C++ Programming Language" (Stroustrup) - both have good descriptions and examples of how to use function pointers. I won't get into the technical details because I'll surely screw them up.

Anyway - the reason you want to pass in only the compare() function without arguments is that the sort() function is going to determine what needs to be compared and use the compare() function to do the comparing. Uhhhh how about a pseudo-example?

Let's say I'm on crack and don't know the alphabet. If you want me to alphabetize a list of words for you, what would you need to give me? The list of words, and instructions telling me how to put them in order. You could tell me that Z comes before Y comes before...B comes before A, and I'd end up reverse-alphabetizing. You could tell me that the order of the alphabet is M, T, Z, Q, B, R, etc.

So yeah, in that lame analogy, I would be the sort() function, and the instructions you give me would be the compare() function. You don't need to provide arguments for the compare() function because I'll handle that on my own - I just need to know how to compare two objects in the list.

It should never be necessary to do it the way you indicated, and I'm pretty sure it's not legal syntax, either. :D

[Edit]
Argh! Of course I took too damn long writing this crap. If I understand what you mean by "inner function", Karate, it sounds like you're on the right track. Yes, the "outer function" - sort() - is going to use the "inner function" - compare() - to determine whether Student_info X's name should come before or after Student_info Y's name. It won't necessarily compare() every single pair of Student_info's - it will do as many compare()'s as it needs to completely sort the list, which could vary quite a bit depending on the sort algorithm being used.

[This message was edited by sorghumking on December 05, 2001 at 17:25.]
 

daKarateKid

Seniorius Lurkius
8
So then does the 'outer' function then do the type matching for the 'inner' function? What if compare was defined as:

code:<HR>
Code:
bool compare(string x, int y, int z)
{
  if (strlen(x) > y * z)
  {
     return true;
  }else{
     return false;
}

Here it is clear that passing the reference to the Student_info struct from sort() into compare() would not have the desired effect. But what stops me from doing it anyway? I guess what I'm asking is, does the compiler demand that the same number and type of arguments used in compare() MUST be supplied by sort()? Since the arguments for sort() seem to be iterators of whatever container, whereas the arguments for compare are struct Student_info, is there something defined by sort() that says: compare() must take two parameters which are pointed to by the iterator parameters of sort(), which in this case are struct Student_info references?

Thanks for your patience. I'm just trying to figure out why sort() knows what to pass to compare :confused:
 

DrPizza

Well-known member
93,870
Since the arguments for sort() seem to be iterators of whatever container, whereas the arguments for compare are struct Student_info, is there something defined by sort() that says: compare() must take two parameters which are pointed to by the iterator parameters of sort(), which in this case are struct Student_info references?
<span style="font-family: 'Lucida Console', monospace;">std::sort()</span> will try to pass the dereferenced iterators to the predicate. If the predicate can't take the right type, it'll generate a compile-time error. The compiler enforces it.
 
Here it is clear that passing the reference to the Student_info struct from sort() into compare() would not have the desired effect. But what stops me from doing it anyway? I guess what I'm asking is, does the compiler demand that the same number and type of arguments used in compare() MUST be supplied by sort()?
Ok, in the simple case, function pointers have to have type. For instance, the parameter will be something like "pointer to a function that takes in two ints and returns bool". Attempt to pass a function which doesn't match that, and it will not compile.

With sort, the function parameter's type can be just about anything, because sort is a template. What that means it that you can pass whatever you want... even an int or a float if you like. BUT, what you pass has to be usable as a function to compare two objects that are to be sorted. If it doesn't, then the compiler will be unable to instantiate sort (so an int or a float wouldn't work). A common alternative to passing a simple function pointer is to pass an object for which the () operator is overloaded. This behaves like a function.
 
Status
Not open for further replies.