devxlogo

Favor the Function Object to the Function Pointer in STL Algorithms

Favor the Function Object to the Function Pointer in STL Algorithms

Many of the STL algorithms have two versions, with one version taking one less parameter than what the second version takes. The one with lesser parameters implies its default logic by using the operator defined for the underlying data type of its argument type.

For example, if you use the sort() algorithm on a vector of strings using the version which takes two paramter then it will sort the vector alphabetically in ascending order using the operator defined for string. But what if you want to sort it on the basis of the length of the strings? In that case, you need to use the version of sort() algorithm which takes three parameters. Pass either a function pointer or a function object as its third argument, which returns true and false according to your logic.

Both the function pointer and function object will accomplish the task, but the function object is the preferrable choice for two reasons:

  1. The invocation of a function through a function pointer is an indirect invocation which prevents the compiler from inlining said function?even if it is a good candidate for inlining. When you use the function object, if the operator() is defined inline and the compiler deems it a suitable candidate for inlining, then the compiler will inline it, thus enhancing performance.
  2. With the function object, you have the choice to keep member data which may help during the operation. It also gives flexibilty to users of intiliazing objects, allowing for different values to be used in the operation. For instance, you may define a function object which helps in finding a string whose length is greater than six or ten by just passing a number to its ctor.
devxblackblue

About Our Editorial Process

At DevX, we’re dedicated to tech entrepreneurship. Our team closely follows industry shifts, new products, AI breakthroughs, technology trends, and funding announcements. Articles undergo thorough editing to ensure accuracy and clarity, reflecting DevX’s style and supporting entrepreneurs in the tech sphere.

See our full editorial policy.

About Our Journalist