Velocity Reviews > C++ > Transform algorithm 1-n, n-1 or m-n

# Transform algorithm 1-n, n-1 or m-n

Diego Martins
Guest
Posts: n/a

 10-18-2006
Hi!

Often, I have some situations when I have to convert a vector of 10
elements to a vector of 30 elements or vice-versa. (the ratio is 1-3)

I want to use the std::transform do to these tasks, but I end up using
std::for_each

Is a special/custom iterator the only way to do that with
std::transform?

Example:

vector<int> source, destiny;
....
now source has 30 elements
destiny.resize(10);

transform(source.begin(),source.end(),destiny.begi n(),ThreeToOneConverter());

** how to write the ThreeToOneConverter functor in order to process and
skip three elements at a time instead of one?

Another example:

vector<int> source, destiny;
....
now source has 10 elements
destiny.resize(30);

transform(source.begin(),source.end(),ThreeAtRowIt erator(destiny),OneToThreeConverter());

it will generate more abominations

Only for_each is the solution to this case?

Diego Martins
HP

=?ISO-8859-15?Q?Juli=E1n?= Albo
Guest
Posts: n/a

 10-18-2006
Diego Martins wrote:

> Often, I have some situations when I have to convert a vector of 10
> elements to a vector of 30 elements or vice-versa. (the ratio is 1-3)
>
> I want to use the std::transform do to these tasks, but I end up using
> std::for_each

Why do you want to use transform? Some good reason or is an exercise?

> Only for_each is the solution to this case?

You can use for example remove_copy_if with a predicate that use his
internal state to tell what elements to copy.

--
Salu2

Fraser Ross
Guest
Posts: n/a

 10-19-2006
For N to 1 conversion I might write a custom transform algorithm taking
a vector of N input iterators. Some other class might be better than
vector. A functors operator() would have to take the object of input
iterators by const ref and return the value to assign from.

BTW sizing the destination is not always necessary if an insert_iterator
is used.

For 1 to 3 I'd use for_each on the source objects and a functor.

Fraser.

Posted Via Usenet.com Premium Usenet Newsgroup Services
----------------------------------------------------------
** SPEED ** RETENTION ** COMPLETION ** ANONYMITY **
----------------------------------------------------------
http://www.usenet.com