# Re: Algorithmic vs design complexity

From:
Vidar Hasfjord <vattilah-groups@yahoo.co.uk>
Newsgroups:
comp.lang.c++
Date:
Tue, 29 Mar 2011 19:11:19 -0700 (PDT)
Message-ID:
Hi Michael,

On Mar 29, 9:20 am, Michael Doubez <michael.dou...@free.fr> wrote:

You could use a proxy for computing the height that memoize the result/
state of the previous computation and call

ProfileHeight height(profile);
BOOST_FOREACH (const Stop& s, stops)
output (s.distance, height (s.distance));

Nice. This is the solution I'm leaning towards. The most important
characteristics are encapsulation and scalability. It scores better in
the latter respect compared to your alternative suggestion (iterator/
callback). E.g. if there is a second query involved in the calculation
which also iterates in the same domain, this solution will support it
nicely.

Here's an implementation for the example I posted to Ralph:

<code>
struct FloorQuery
{
Building* b;
int floor;
int height;

FloorQuery (Building& br)
: b (&br), floor (0), height (0)
{height += b->floors [0].height;}

int operator () (int h)
{
while (h > height)
{
++floor;
height = (floor == b->floors.size ()) ?
numeric_limits <int>::max () :
height + b->floors [floor].height;
}
return floor;
}
};

cout << "\nParallel traversal 2:\n\n";
{
FloorQuery get_floor (building);
for (int i = 0; i != no; ++i)
{
int h = objects [i].height;
output (h, get_floor (h));
}
}
</code>

Another solution is to have profile provides the calculation of
distance from a sorted iterator range, written in output iterator (or
functor):

You mean "calculation of height for a sorted sequence of distances
given by an iterator range", I presume. It is an interesting
alternative, but it seems less scalable than your previous suggestion.
For example, what if our function involved querying both the height
and curvature of the profile? You could use result vectors to hold the
results of the queries and then compute on those, but this requires
extra memory and seems less elegant than your previous suggestion. The
callback alternative would not scale at all, as far as I can see,
although the outer function could be implemented as a functor and
passed to a generic algorithm such as for_each. For example,

for_each(objects, objects + no, CalcFloor (building));