Boost logo

Boost :

From: farrow_at_[hidden]
Date: 2001-08-09 14:22:39

Using STL algorithms...
I am unable to deduce a way of combining or reducing sequence
containers into a single result or filtering arbitrary iterators with
a predicate. So I have created these...

REDUCE: applies a binary operator where the first argument is the
current intermediate result and the second is each value in the
sequence. The result of each function application becomes the new


vector<int> nums; //contains { 1, 2, 3 }
int result = reduce(nums.begin(), nums.end(), plus<int>(), 0);
//result = 6

COMBINE: applies the plus operator to the elements in a sequence with
a separator. Mostly useful for containers of strings -- but not
limited to that.


string sep("|");
vector<string> strs; //contains { "a", "b", "c" }
string result = combine(strs.begin(), strs.end(), sep)
//result = "a|b|c"

FILTER: a wrapper for an iterator that applies a predicate functor.
The resulting iterator only stops at objects that pass the predicate.

vector<int> nums; //contains { 1, 15, 2, 10, 3 }
int result = reduce(filter(nums.begin(),
                    nums.end(), plus<int>(), 0);
//result = 6

GUARD: is the complement of FILTER.
The resulting iterator only stops at objects that FAIL the predicate.

I have not found these (or the like) in STL or after looking thru
several on-line repositories -- Boost and others recommended by
"Effective STL" (by Meyers).

I don't contend that these interfaces are perfect and
I am happy to be refered to someone else's work.


Rob Farrow

Boost list run by bdawes at, gregod at, cpdaniel at, john at