Re: function object for [] and *
On Jun 23, 10:34 pm, Noah Roberts <u...@example.net> wrote:
AnonMail2...@gmail.com wrote:
On Jun 23, 2:22 pm, Rares Vernica <ra...@ics.uci.edu> wrote:
I need help to replace the following code:
int *idx; //...
for (int i = 0; i < n; i++, ++out)
out = in[idx[i]];
with something like:
int *idx; //...
std::transform(idx, idx + n, out, ...);
I think the operator for transform should look something like:
__gnu_cxx::compose1(in[], *idx)
So, I think, I need a function object to apply the []
operator to "in", given an int and another one to apply the
* operator to each element in "idx".
Here's a first cut assuming the contents of in and out are
doubles. If they're not, change accordingly...
struct Functor
{
std::vector<double> const & m_in;
// constructor
Functor (std::vector<double> const & in) : m_in (in)
{}
// functor operator
double operator () (int i) const
{
return in [i];
}
}
std::transform (idx, idx + n, out, Functor (in));
Make sure out has enough room in out or use std::back_inserter (out).
You might also try something like so (untested):
std::transform(idx, idx+n, out, boost::bind(&in_type::operator[], in, _1)=
);
Which won't work if in_type is a C style array (or a pointer).
(Otherwise, a simple, direct application of boost::bind is still
readable enough that I would consider it more or less
acceptable. Although I don't see anything wrong with the
original code, and I'd probably wait until we get lambda
expressions to upgrade it.)
--
James Kanze (GABI Software) email:james.kanze@gmail.com
Conseils en informatique orient=E9e objet/
Beratung in objektorientierter Datenverarbeitung
9 place S=E9mard, 78210 St.-Cyr-l'=C9cole, France, +33 (0)1 30 23 00 34