Noeud:Some Predefined Function Objects, Noeud « Next »:, Noeud « Previous »:Function Objects - in a Nutshell, Noeud « Up »:Generic Algorithms and Function Objects



Some Predefined Function Objects

You might actually be wondering why we should even bother using function objects, since the examples so far have been fairly simple and non-informative. Well, you can use them with most of the containers we have already seen. In Container Summary, one of the constructors for set and map passed in a comparison object; list provides it's own sort method, which you could pass a comparrison object to tell it how to sort data. Well, we can use any of the comparison function objects given here; so, instead of ordering using less-than (the default ordering), we can instead use greater, for example:

       /* Create a set in which we sort elements using 'greater'
        * rather than 'less than': */
       std::set<int, greater<int>()> some_set;
     
       /* Now create a list: */
       std::list<int> some_list;
       /* ... add some elements to the list... */
     
       /* Sort elements from greatest to least: */
       some_list.sort(greater<int>());
     

The above example demonstrates (without going into too much detail) how the greater function object can be used to change the sorting criterion for a set, as well as sorting a list using greater. greater, along with a number of other predefined function objects, are detailed in Function Object Summary.

However, there are also a few other function objects that are worth metioning here, and are very useful. These are covered in the next section.