[Effective-cpp] Item 1: Uses and Abuses of vector
Mark Radford
mark at twonine.co.uk
Wed Oct 27 05:55:17 EDT 2004
On Sat, 23 Oct 2004, at 10:32:06, Paul Grenyer <paul at paulgrenyer.co.uk>
writes
>I have become more and more disillusioned with this particular idea
>recently. It's fine for the examples in the book, where standard
>library predicates such as, ostream_iterator are used
This isn't a predicate. A predicate is a function object that returns
true or false - such as that used in std::find_if.
>(although I hate having to look things up!), but for custom predicates
>I don't think it's so good.
This surprises me, because I have found I can be far more expressive -
or at least try to be more expressive - when writing my own function
objects.
>The three main problems I have using algorithms and my own predicates
>are:
>
>1. Coming up with a good descriptive name that describes what the
>predicate does in order to remove the need for the maintainer to look
>for its implementation.
This isn't a problem with naming your own function objects - the problem
is that it's just hard to come up with meaningful names for things in
all but the simplest situations.
A great advantage of making the effort to name your own function objects
is that you capture a single level of abstraction within a piece of
code. For example:
for_each(c.begin(), c.end(), write(cout));
This simply tells you that each element in the range is being written to
cout, whereas (assuming the presence of suitable typedefs):
for (const_iterator i = c.begin(); i != c.end(); ++i)
{
}
combines what you're trying to do, with how you're doing it. For someone
trying to understand what this code does, the code in the braces is more
noise than signal.
Note that I personally would use for_each and code up a function object
called "write" rather than copy to an ostream_iterator, because it leads
to the code effectively being its own comment.
>2. Where to put the predicate so it's easy for the maintainer to find.
>If it's in an anonymous namespace at the top of the file the maintainer
>has to scroll up for it, if it's above the (for arguments sake) member
>function definition, it's untidy.
First, the problem here disorganised thinking more than anything else.
You're trying to understand too much at once. Understand first what the
code does, then delve into how it does it if necessary.
Second, use the available tools effectively. One simple approach is to
print off the function object(s) (presumably located in the unnamed
namespace), and use the hard copy for reference (if necessary) while
working on the code that uses them.
>3. Often using a predicate results in more code.
Yes, but traded against better organised and more expressive code!
Just my view of the world :-)
Regards,
Mark.
--
Mark Radford
twoNine Computer Services Ltd - Software Development & Consultancy
http://www.twonine.co.uk
More information about the Effective-cpp
mailing list