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

Discussion in 'C++' started by Diego Martins, Oct 18, 2006.

1. ### Diego MartinsGuest

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.begin(),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(),ThreeAtRowIterator(destiny),OneToThreeConverter());

it will generate more abominations

Only for_each is the solution to this case?

Diego Martins
HP

Diego Martins, Oct 18, 2006

2. ### =?ISO-8859-15?Q?Juli=E1n?= AlboGuest

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

=?ISO-8859-15?Q?Juli=E1n?= Albo, Oct 18, 2006

3. ### Fraser RossGuest

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

Fraser Ross, Oct 19, 2006

## Want to reply to this thread or ask your own question?

It takes just 2 minutes to sign up (and it's free!). Just click the sign up button to choose a username and then you can ask your own questions on the forum.