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
Student_info.cc
grades.cc
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:
Why is this not necessary? Is it ever necessary, or allowable to do it the way I've outlined? Thanks.
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.