Philip Potter <philip.potter@xilinx.comwrote:
Quote:
I'm reading about the std::for_each() function in TC++PL, 3rd Ed. It seems
like a good idea, but in practice I can never see a way to bend it to my
wishes without writing huge function objects. The same goes for most things
in <algorithm>, though I don't know if I'm just not used to it or if it
really is ugly.
>
Specific question:
I have a vector of objects and I'd like to send them all to std::cout. Is
there a way of doing this using standard binders and adapters? I have tried
the following:
std::for_each(myvector.begin(), myvector.end(), std::cout.operator<<);
std::for_each(myvector.begin(), myvector.end(),
bind1st(mem_fun_ref(&ostream::operator<<),std::cou t));
..but that didn't work. Would it have worked if operator<<(ostream &, myobj)
was a regular function? Is there a clean, readable, terse way of writing
what I want to write?
If you have defined
std::ostream& operator<<(std::ostream&, const YourObj&);
then for a std::vector<YourObjyou can do:
#include <algorithm>
#include <iterator>
std::vector<YourObjobj_vect;
// ...
std::copy(obj_vect.begin(),
obj_vect.end(),
std::ostream_iterator<YourObj>(std::cout, "\n"));
where "\n" specifies the delimiter to place between vector entries.
Quote:
General questions:
When do you prefer to use std::for_each(), when do you prefer to use a for
loop over iterators, and when do you prefer to use a for loop over indices?
Honestly, I almost never use std::for_each(). I use iterators when I
can, unless there is a situation in which I have to deal with parallel
data structures for some reason. With parallel data structures, I mean
something like:
std::vector<inti_vect;
std::vector<doubled_vect;
for (std::vector<int>::size_type i = 0; i != i_vect.size(); ++i) {
something = i_vect[i] * d_vect[i];
}
where i_vect[i] and d_vect[i] both store some property about the same
logical entity, but for some design reason a
std::vector<IntDoubleStructwasn't the best idea.
Quote:
Is there a textbook which covers good (moral) usage of the members of
<algorithmand <functional>?
Not sure on specific book recommendations. Maybe check out the reviews
on
http://accu.org/ .
--
Marcus Kwok
Replace 'invalid' with 'net' to reply