| herold (10) | |||
|
Hi, Here is my program definition: Create a student class that include a student's first name and his roll_number.Create five objects of this class and store them in a list.Write a program using this list to display the student name if the roll_number is going and voice-versa. I have written following code.
In find function i want to apply it to "name" member of class "student". How it is possible ? | |||
|
|
|||
| Cubbi (1927) | |||||
This is really a job for std::map. If you must search a list, the way to do that is to provide find_if() with a functor that compares student names: q=find_if(s, e, [&](const student& s){return s.name == temp;});online demo: http://ideone.com/ojg0cT or (if you only have an old compiler), you could write that out by hand:
demo: http://ideone.com/qnNyQC std::find() would only work for you if you provide an operator== that compares students and returns true if their names match, which may or may not be a good thing..
demo: http://ideone.com/DLLNkV | |||||
|
Last edited on
|
|||||
| herold (10) | |||
|
Okay. I got some of your point.But let me be frank i didn't understand what you have done in this statement [code]q=find_if(s, e, [&](const student& s){return s.name == temp;});[\code] what is meaning of
| |||
|
|
|||
| Cubbi (1927) | |
| The first example uses modern (2011) language features. If you don't have them in your books, fall back to the second and third examples. | |
|
|
|
| herold (10) | |||
Thank you
For second what will the
| |||
|
Last edited on
|
|||
| Cubbi (1927) | |
|
The predicate is a function object that you, the programmer, are supplying. It is supposed to return true when invoked with the record you're looking for and false when invoked with any other record. find_if() will keep call your predicate on every element of the list until it returns true. The second example shows how such predicates were written in 1998: as a class with an overloaded function-call operator. It returns true when called with a record whose .name equals the value passed in the constructor. The first example shows the new shorthand syntax which does the same thing (it creates a class with an overloaded function-call operator). Google "C++ lambda expression" for details. There are a few more ways to write predicates, since this is such a common task. The boost library has some convenient ones. | |
|
|
|