By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
424,952 Members | 1,935 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 424,952 IT Pros & Developers. It's quick & easy.

Using function objects in own algorithm

P: n/a
I now know how to compose a function object for some standard
algorithms, e.g., std::sort(). However, I cannot find an explanation
of how to use a function object in my own code of an algorithm. All
the links I find focus on the former. Could anyone explain this to me
and/or point me to a clear explanation?

For example, how could I use the function object instantiated from the
class "less metric1" below?

What I want to do is to tell a function (e.g., do-something()) to do
some math based on a particular object`s attribute (out of several
attributes). It is very similar to how std::sort uses it (on the
surface), but I do not know how sort() uses a function object
internally.

Thanks, Alan

class measurement
{
public:
double metric1, metric2, metric3;
};
class less_metric1 : binary_function<measurement, measurement, bool>
{
public:
return_type operator()(const measurement& a, const measurement&
b)
{
return a.metric1 < b.metric1;
}

Jun 18 '07 #1
Share this Question
Share on Google+
1 Reply


P: n/a
On 2007-06-18 18:16, Alan wrote:
I now know how to compose a function object for some standard
algorithms, e.g., std::sort(). However, I cannot find an explanation
of how to use a function object in my own code of an algorithm. All
the links I find focus on the former. Could anyone explain this to me
and/or point me to a clear explanation?

For example, how could I use the function object instantiated from the
class "less metric1" below?

What I want to do is to tell a function (e.g., do-something()) to do
some math based on a particular object`s attribute (out of several
attributes). It is very similar to how std::sort uses it (on the
surface), but I do not know how sort() uses a function object
internally.

Thanks, Alan

class measurement
{
public:
double metric1, metric2, metric3;
};
class less_metric1 : binary_function<measurement, measurement, bool>
{
public:
return_type operator()(const measurement& a, const measurement&
b)
{
return a.metric1 < b.metric1;
}
Using templates:

#include <iostream>
#include <functional>

template<class Comp>
int doSomething(int a, int b)
{
Comp C;
if (C(a,b))
return a;
else
return b;
}

int main()
{
int a = 5;
int b = 6;

std::cout << doSomething<std::less<int(a, b)
<< std::endl;
std::cout << doSomething<std::greater<int(a, b)
<< std::endl;

}

What you do is to create an instance of the functor and use the
()-operator in the function.

--
Erik Wikström
Jun 18 '07 #2

This discussion thread is closed

Replies have been disabled for this discussion.