473,385 Members | 1,610 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,385 software developers and data experts.

sorting a vector, functors, and std::binary_function

I used to just use a plain old function pointer is a call to
std::sort.

My colleagues are telling me that I need to use a "functor". Ok, I
google and see that a functor is a class with a public method,
operator () that does the comparison. Fine, no problem. What they fail
to tell me is, what is the advantage to wrapping some comparison
function in a class and calling it operator()?

I also read that "functors" are supposed to be a class that wraps a
function pointer and additionally holds a state. What kind of state,
what is the typical scenario? I don't see any state data in any of my
colleagues code...

I also googled for examples on doing a sort upon a vector using this
concept of a functor to get the syntax correct. I notice that one
example derives his functor from std::binary_function. Google
binary_function and see that it is described as "a base class for a
functor", well that doesn't tell me much. Why do some of the examples
I've found derive from std::binary_function while others do not?

Thanks!
Nov 28 '07 #1
4 2718
Christopher wrote:
I used to just use a plain old function pointer is a call to
std::sort.

My colleagues are telling me that I need to use a "functor". Ok, I
google and see that a functor is a class with a public method,
operator () that does the comparison. Fine, no problem. What they fail
to tell me is, what is the advantage to wrapping some comparison
function in a class and calling it operator()?
It can be inlined by std::sort().

Using a function pointer is perfectly legitimate. A functor is
"anything that looks and behaves like a function".
Nov 28 '07 #2
Christopher wrote:
What they fail
to tell me is, what is the advantage to wrapping some comparison
function in a class and calling it operator()?
You can't pass a (non-static) member function since the hidden object
pointer isn't typically part of the function's pointer; hence this
mechanism.
I think that's the main reason -- basically a workaround.
Nov 28 '07 #3
Christopher wrote:
I also read that "functors" are supposed to be a class that wraps a
function pointer and additionally holds a state. What kind of state,
what is the typical scenario?
Please consider the code below to be pseudo-code.

// Contrived textbook example with constant state:

struct mul {
const int multiplier;
mul(int multiplier_): multiplier(multiplier_) {}
void operator()(int n) { n *= multiplier; }
};

mul quadruple(4);
mul tripple(3);

vector<inti = .......;
foreach(i.begin, i.end, quadruple);
// You could imagine non-const state in something like.

struct find_min_max .......
log_min_max minmax;
foreach(i.begin(), i.end(), minmax);
// A real example that I use is:

charset_converter utf8_to_8859_1("utf8","iso8859-1");

while (!end-of-input) {
s += utf8_to_8859_1(next_bit);
}

Here the functor state is any partial multi-byte characters.

Regards,

Phil.
Nov 28 '07 #4
On Nov 28, 6:56 pm, Christopher <cp...@austin.rr.comwrote:
I used to just use a plain old function pointer is a call to
std::sort.
My colleagues are telling me that I need to use a "functor".
Don't believe them.
Ok, I google and see that a functor is a class with a public
method, operator () that does the comparison. Fine, no
problem. What they fail to tell me is, what is the advantage
to wrapping some comparison function in a class and calling it
operator()?
The use of a functor means that there is a separate
instantiation of std::sort for each function (since each functor
has a different type), and that the actual function is known in
the instantiation of std::sort. This can (in some cases) result
in slightly faster code, because the compiler can inline the
comparison. It can (in certain other cases) result in code
bloat, because the compiler must generate a separate
instantiation of the std::sort function template for each
different function. 99% of the time, it doesn't matter.
I also read that "functors" are supposed to be a class that wraps a
function pointer and additionally holds a state. What kind of state,
what is the typical scenario? I don't see any state data in any of my
colleagues code...
First, it doesn't wrap a function pointer; it has a member
function which does the job. Secondly, it's very, very rare for
a binary predicate to contain state. Other functors often do,
however: the predicate for std::find_if may (in fact, usually
will) contain the key you're looking for. And even binary
precidates can contain state; if you want to do a case
insensitive comparison of strings, for example, you might embed
a pointer to the desired std::ctype facet in the predicate, for
example.
I also googled for examples on doing a sort upon a vector
using this concept of a functor to get the syntax correct. I
notice that one example derives his functor from
std::binary_function. Google binary_function and see that it
is described as "a base class for a functor", well that
doesn't tell me much. Why do some of the examples I've found
derive from std::binary_function while others do not?
No real reason. When you start composing several functors, it
becomes necessary that the functors being composed contain
typedefs indicating their argument and return value types. The
class std::binary_function provides these, but you can also
provide them manually. And they're only used when you start
composing, using things like std::bind2nd. Which means that if
you're writing a local functor, which can't be seen outside your
source, there's no real point in them at all.

--
James Kanze (GABI Software) email:ja*********@gmail.com
Conseils en informatique orientée objet/
Beratung in objektorientierter Datenverarbeitung
9 place Sémard, 78210 St.-Cyr-l'École, France, +33 (0)1 30 23 00 34
Nov 29 '07 #5

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

6
by: Greg Lilley | last post by:
I have an application where I want to remove all of the items that are in one vector from a second vector. In the following short program, my objective is to remove all of ourCards from...
0
by: marco_segurini | last post by:
Hi, I am trying to solve this problem: I have a vector V1 that is not empty and a vector V2 that contains some iterator that point to V1 elements. Now I want to remove the V1 elements that V2...
18
by: John Black | last post by:
Hi, I am not familiar with for_each very well, suppoase I have a vector<pair<unsigned int, unsigned int> > vec1 and the contents are {<0x00000000, 0x000000FF>, <0x10000000, 0x2FFFFFFF>} what...
18
by: Matthias Kaeppler | last post by:
Hi, in my program, I have to sort containers of objects which can be 2000 items big in some cases. Since STL containers are based around copying and since I need to sort these containers quite...
24
by: toton | last post by:
Hi, I want to have a vector like class with some additional functionality (cosmetic one). So can I inherit a vector class to add the addition function like, CorresVector : public...
10
by: JDT | last post by:
Hi, Can someone provide me an example that uses std::max_element() (probablly the predicate version) to return the max "absolute" integer in a vector? Your help is much appreciated. Tony ...
9
by: laikon | last post by:
dear, all: below is a function with a parameter of function pointer. void f(int a, int b, int (*fp)(int, int)) { std::cout << fp(a, b) << std::endl; }
1
by: Frank Bergemann | last post by:
i don't manage to get this compiled: // shall map compare operator ids to proper std::binary_function's // for this instantiated for various types template <typename ForType> struct...
2
by: L. Kliemann | last post by:
* Jerry Coffin <jcoffin@taeus.com>: My question was mostly out of curiosity. I've been working with C++ for about half a year now, and I came across several occasions where my first...
0
by: Charles Arthur | last post by:
How do i turn on java script on a villaon, callus and itel keypad mobile phone
0
by: aa123db | last post by:
Variable and constants Use var or let for variables and const fror constants. Var foo ='bar'; Let foo ='bar';const baz ='bar'; Functions function $name$ ($parameters$) { } ...
0
by: ryjfgjl | last post by:
If we have dozens or hundreds of excel to import into the database, if we use the excel import function provided by database editors such as navicat, it will be extremely tedious and time-consuming...
0
by: ryjfgjl | last post by:
In our work, we often receive Excel tables with data in the same format. If we want to analyze these data, it can be difficult to analyze them because the data is spread across multiple Excel files...
0
by: emmanuelkatto | last post by:
Hi All, I am Emmanuel katto from Uganda. I want to ask what challenges you've faced while migrating a website to cloud. Please let me know. Thanks! Emmanuel
0
BarryA
by: BarryA | last post by:
What are the essential steps and strategies outlined in the Data Structures and Algorithms (DSA) roadmap for aspiring data scientists? How can individuals effectively utilize this roadmap to progress...
0
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can...
0
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers,...
0
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.