473,398 Members | 2,335 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,398 software developers and data experts.

<algorithm> transform modification

Hi!

I tried to modify the transform algorithm in a way that it doesn't
take iterators, but a reference to a container class and a value,
because Mostly I need to do an operation of a container and a single
number (e.g. multiply all the values in a vector by 3 or so).
So, this is my intent:

#ifndef ALGORITHM_EXT_HH
#define ALGORITHM_EXT_HH

#include<iterator>

namespace std
{
template<typename _Tp, template<typename> class _Container,
typename _Tpval, typename _BinaryOperation>
_Container<_Tp>&
transform(_Container<_Tp>& __cont, const _Tpval& __val,
_BinaryOperation __binary_op)
{
_Container<_Tp>::iterator __iter=__cont.begin();
_Container<_Tp>::iterator __end=__cont.end();
for ( ; __iter != __end; ++__iter)
*__iter = __binary_op(*__iter, __val);
return __cont;
}

} //namespace std

#endif //ALGORITHM_EXT_HH

The error message I get from g++ (GCC) 3.3 20030226 (prerelease) (SuSE
Linux) is:
linux@earth:~/> g++ mod2pnm.cc -o mod2pnm
In file included from mod2pnm.cc:16:
algorithm_ext.hh: In function `_Container<_Tp>&
std::transform(_Container<_Tp>&, const _Tpval&, _BinaryOperation)':
algorithm_ext.hh:32: error: parse error before `=' token
algorithm_ext.hh:33: error: parse error before `=' token
algorithm_ext.hh: In function `_Container<_Tp>&
std::transform(_Container<_Tp>&, const _Tpval&, _BinaryOperation)
[with _Tp
= double, _Container = std::vector, _Tpval = double,
_BinaryOperation =
std::minus<double>]':
mod2pnm.cc:144: instantiated from here
algorithm_ext.hh:34: error: `__end' undeclared (first use this
function)
algorithm_ext.hh:34: error: (Each undeclared identifier is reported
only once
for each function it appears in.)
algorithm_ext.hh:34: error: `__iter' undeclared (first use this
function)
Any ideas, what's wrong? I tried all night long!

Thanks, Steffen
Jul 19 '05 #1
20 3803
WW
Steffen Brinkmann wrote:
#ifndef ALGORITHM_EXT_HH
#define ALGORITHM_EXT_HH

#include<iterator>

namespace std
{
You are not allowed to place anything into the std namespace!
template<typename _Tp, template<typename> class _Container,
Standard container templates take many more arguments.
typename _Tpval, typename _BinaryOperation>
_Container<_Tp>&
transform(_Container<_Tp>& __cont, const _Tpval& __val,
_BinaryOperation __binary_op)
{
_Container<_Tp>::iterator __iter=__cont.begin(); typename _Container<_Tp>::iterator __iter=__cont.begin();
_Container<_Tp>::iterator __end=__cont.end(); Ditto
for ( ; __iter != __end; ++__iter)
*__iter = __binary_op(*__iter, __val);
return __cont;
}

} //namespace std

#endif //ALGORITHM_EXT_HH

The error message I get from g++ (GCC) 3.3 20030226 (prerelease) (SuSE
Linux) is:

[SNIP]

Seems that 3.3 has two phase name lookup implemented or at least it refuses
to guess what is a type anymore.

--
WW aka Attila
Jul 19 '05 #2
Steffen Brinkmann wrote:
I tried to modify the transform algorithm in a way that it doesn't
take iterators, but a reference to a container class and a value,
because Mostly I need to do an operation of a container and a single
number (e.g. multiply all the values in a vector by 3 or so).


In addition to WW's good comments, I thought I might add:

You might try out std::bind2nd in <functional> and stick with the
std::transform:

std::transform(v.begin(), v.end(), v.begin(),
std::bind2nd(std::multiplies<int>(), 3));

If you get into more complicated operations, boost::bind might provide
an answer ( www.boost.org ). boost::bind may eventually be
standardized. It has been voted into the first library technical report
which indicates an official interest in this library. The above
transform translates into bind with:

std::transform(v.begin(), v.end(), v.begin(),
boost::bind(std::multiplies<int>(), _1, 3));

-Howard
Jul 19 '05 #3
"WW" <wo***@freemail.hu> wrote in message
news:bk**********@phys-news1.kolumbus.fi...
[...]
You are not allowed to place anything into the std
namespace!
[...]


Except specializations of std::less<>, and perhaps a few other
things.

Dave
Jul 19 '05 #4
In article <bk**********@phys-news1.kolumbus.fi>, wo***@freemail.hu
says...

[ ... ]
You are not allowed to place anything into the std namespace!


Not so -- you are specifically allowed to add (partial or complete)
specializations of standard library templates to namespace std. See $
17.4.3.1/1 for the exact requirements.

--
Later,
Jerry.

The universe is a figment of its own imagination.
Jul 19 '05 #5
WW
David B. Held wrote:
"WW" <wo***@freemail.hu> wrote in message
news:bk**********@phys-news1.kolumbus.fi...
[...]
You are not allowed to place anything into the std
namespace!
[...]


Except specializations of std::less<>, and perhaps a few other
things.


Yeah. But they have to be specializations, not new things. And I prefer to
mentioned them for those, who know they can ask this question. :-)

--
WW aka Attila
Jul 19 '05 #6
WW
Jerry Coffin wrote:
In article <bk**********@phys-news1.kolumbus.fi>, wo***@freemail.hu
says...

[ ... ]
You are not allowed to place anything into the std namespace!


Not so -- you are specifically allowed to add (partial or complete)
specializations of standard library templates to namespace std. See $
17.4.3.1/1 for the exact requirements.


You are not placing them into the standard namespace. They are there and
you are allowed to specialize them. I prefer to put it this way because I
have met people (hearing there is exception) kept putting declarations of
new things there.

--
WW aka Attila
Jul 19 '05 #7
WW wrote in news:bk**********@phys-news1.kolumbus.fi:
David B. Held wrote:
"WW" <wo***@freemail.hu> wrote in message
news:bk**********@phys-news1.kolumbus.fi...
[...]
You are not allowed to place anything into the std
namespace!
[...]


Except specializations of std::less<>, and perhaps a few other
things.


Yeah. But they have to be specializations, not new things. And I
prefer to mentioned them for those, who know they can ask this
question. :-)


IIUC you can specialize *any* template in namespace std aslong as
the specialization is dependant an a UDT not defined in namespace std.
I.e. this should be Ok:

class myclass {};
namespace std
{
template < typename Alloc >
class vector< myclass, Alloc >
{
};
}

Rob.
--
http://www.victim-prime.dsl.pipex.com/
Jul 19 '05 #8
WW
Rob Williscroft wrote:
[SNIP]
IIUC you can specialize *any* template in namespace std aslong as
the specialization is dependant an a UDT not defined in namespace std.
I.e. this should be Ok:

class myclass {};
namespace std
{
template < typename Alloc >
class vector< myclass, Alloc >
{
};
}


Chapter and verse?

--
WW aka Attila
Jul 19 '05 #9
WW wrote in news:bk**********@phys-news1.kolumbus.fi:
Rob Williscroft wrote:
[SNIP]
IIUC you can specialize *any* template in namespace std aslong as
the specialization is dependant an a UDT not defined in namespace std.
I.e. this should be Ok:

class myclass {};
namespace std
{
template < typename Alloc >
class vector< myclass, Alloc >
{
};
}


Chapter and verse?


17.4.3.1/1 - but I missed "... results in undefined ... and unless the
specialization meets the standard library requirements for the original
...." so my example wouldn't be Ok (that "IIUC" wasn't wasted after all).

Rob.
--
http://www.victim-prime.dsl.pipex.com/
Jul 19 '05 #10
WW
Rob Williscroft wrote:
[SNIP]
17.4.3.1/1 - but I missed "... results in undefined ... and unless the
specialization meets the standard library requirements for the
original ..." so my example wouldn't be Ok (that "IIUC" wasn't wasted
after all).


That's what I thought. :-)

--
WW aka Attila
Jul 19 '05 #11
Jerry Coffin <jc*****@taeus.com> wrote in message news:<MP************************@news.clspco.adelp hia.net>...

See $ 17.4.3.1/1 for the exact requirements.


Where do I find that?

Steffen
Jul 19 '05 #12
"WW" <wo***@freemail.hu> wrote in message news:<bk**********@phys-news1.kolumbus.fi>...
template<typename _Tp, template<typename> class _Container,
Standard container templates take many more arguments.


I copied that method from Bruce Eckel's "Thinking in C++". An dit
works... Do you mean an explicit Reference?
_Container<_Tp>::iterator __iter=__cont.begin();

typename _Container<_Tp>::iterator __iter=__cont.begin();


THANKSALOT! That was it! typical case of blindness after hours of
nightly programming!

Seems that 3.3 has two phase name lookup implemented or at least it refuses
to guess what is a type anymore.


Why?

Thanks again, Steffen
Jul 19 '05 #13
Howard Hinnant <hi*****@metrowerks.com> wrote in message news:<hi***************************@syrcnyrdrs-02-ge0.nyroc.rr.com>...
You might try out std::bind2nd in <functional> and stick with the
std::transform:

std::transform(v.begin(), v.end(), v.begin(),
std::bind2nd(std::multiplies<int>(), 3));

That was my first attempt and it worked fine. but I like
short-to-write function calls like:

std::transform(v,value,std::multiplies<int>());
If you get into more complicated operations, boost::bind might provide
an answer ( www.boost.org ). boost::bind may eventually be
standardized. It has been voted into the first library technical report
which indicates an official interest in this library. The above
transform translates into bind with:

std::transform(v.begin(), v.end(), v.begin(),
boost::bind(std::multiplies<int>(), _1, 3));


Aha, interesting site, thank you!

Steffen
Jul 19 '05 #14
> You might try out std::bind2nd in <functional> and stick with the
std::transform:

std::transform(v.begin(), v.end(), v.begin(),
std::bind2nd(std::multiplies<int>(), 3));


Is there a reason for not using for_each? I have been wondering if for_each
is faster.

Fraser.
---
Outgoing mail is certified Virus Free.
Checked by AVG anti-virus system (http://www.grisoft.com).
Version: 6.0.520 / Virus Database: 318 - Release Date: 18/09/2003
Jul 19 '05 #15
In article <f9**************************@posting.google.com >,
s.***@web.de says...
Jerry Coffin <jc*****@taeus.com> wrote in message news:<MP************************@news.clspco.adelp hia.net>...

See $ 17.4.3.1/1 for the exact requirements.


Where do I find that?


That's section 17.4.3.1, paragraph 1, of the C++ standard. If you don't
have a copy, you can get one as a PDF file for $18US from
webstore.ansi.org (this requires a credit or debit card they'll accept).

The DIN only seems to sell the paper version, at a much less attractive
price (242,70 Euros). You can also get it direct from the ISO (in
either PDF or paper format) for 364 CHF, which is roughly typical for a
paper copy, but clearly pretty high for a PDF.

Various other national bodies sell it as well, but I don't know of any
that sell the PDF for less than ANSI does. If you decided to get the
paper version, shipping costs would probably favor buying locally.

--
Later,
Jerry.

The universe is a figment of its own imagination.
Jul 19 '05 #16
In article <3f******@news.greennet.net>,
"Fraser Ross" <fraserATmembers.v21.co.unitedkingdom> wrote:
You might try out std::bind2nd in <functional> and stick with the
std::transform:

std::transform(v.begin(), v.end(), v.begin(),
std::bind2nd(std::multiplies<int>(), 3));


Is there a reason for not using for_each? I have been wondering if for_each
is faster.


I think it would be a matter of convenience rather than performance.
for_each could certainly be used here. But the use of for_each looks
more complicated to me than does transform.

On the inside transform will do something like:

*target = op(*source);

whereas for_each will do something like:

op(*source);

In our example, we're wanting to do:

*target = *target * 3;

or maybe:

*target *= 3;

So to use for_each you have to cook up a functor that takes a single
argument and performs the desired operation (both times and assign, or
the combined *=). There is no std::multiply_assign, but you could roll
your own:

template <class T, class U = T>
struct multiply_assign
: public std::binary_function<T, U, T>
{
T& operator()(T& t, const U& u) const
{return t *= u;}
};

Then you could use this with for_each and bind2nd like:

std::for_each(v.begin(), v.end(),
std::bind2nd(multiply_assign<int>(), 3));

I would expect this example to have the same performance as the
transform version, but I have not tested that expectation.

-Howard
Jul 19 '05 #17
transform might be as fast if return value optimisation is used. I would
prefer another algorithm for when the output iterator is the same as an
input iterator and two ranges are used. That isn't the situation the OP
has. e.g.

template <class ForwardIterator, class InputIterator, class BinaryOperation>
BinaryOperation transform_each (ForwardIterator first1, InputIterator last1,
InputIterator first2, BinaryOperation binary_op) {
while (first1 != last1) {
binary_op(*first1, *first2);
++first1, ++first2;
}
return binary_op;
}
Fraser.
---
Outgoing mail is certified Virus Free.
Checked by AVG anti-virus system (http://www.grisoft.com).
Version: 6.0.520 / Virus Database: 318 - Release Date: 18/09/2003
Jul 19 '05 #18
Sorry, pressed the wrong key.

Is there a reason for not using for_each?


As I said, I'd have to write sth like

void f(double val){ val+=2.;}

and then call

for_each(v.begin(),v.end(),f());

What, if it is noct 2. but a value that is calculated at runtime?

Steffen
Jul 19 '05 #19
Steffen Brinkmann wrote:
Sorry, pressed the wrong key.
Is there a reason for not using for_each?

As I said, I'd have to write sth like

void f(double val){ val+=2.;}

and then call

for_each(v.begin(),v.end(),f());

What, if it is noct 2. but a value that is calculated at runtime?

Steffen


use a functor... There's probably a standard one that I can't remember at this time, but here's one,
and I realize I may have the syntax/semantics of for_each() slightly messed up. Please have pity, gurus!

struct add_value {
double val;
add_value (val_) : val(val_) { }
double operator()(double& d) { return d += val; }
}

then you can call:

for_each(v.begin(), v.end(), add_value(some_calculated_value_here));
Jul 19 '05 #20
Hi!

Thank you all for your postings and learned a lot.
My solution is to use bind2nd(..) and only the stl without specialisation.

Thanks again

I'm out of here, Steffen
Jul 19 '05 #21

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

Similar topics

5
by: google | last post by:
Hi All, I'm just getting started learning to use <algorithm> instead of loads of little for loops, and I'm looking for a bit of advice/mentoring re: implementing the following... I have a...
7
by: Wei | last post by:
Hi all, I found out I can use the max function which is defined in STL <algorithmwithout including this header in my program. The compilers I used are GNU g++ 3.4.4 and Visual Studio C++ 2005. ...
10
by: arnuld | last post by:
WANTED: /* C++ Primer - 4/e * * Exercise: 9.26 * STATEMENT * Using the following definition of ia, copy ia into a vector and into a list. Use the single iterator form of erase to...
11
by: Gerald I. Evenden | last post by:
Working on a Kubuntu 64bit system "c++ (GCC) 4.0.3". The following simple program extracted from p.497 & 499 of N.M.Josurris' "The C++ Standard Library ... " (file t.cpp): 1 #include <string>...
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...
1
by: nemocccc | last post by:
hello, everyone, I want to develop a software for my android phone for daily needs, any suggestions?
0
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However,...
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...
0
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows...
0
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each...

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.