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

D

Diego Martins

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
 
?

=?ISO-8859-15?Q?Juli=E1n?= Albo

Diego said:
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.
 
F

Fraser Ross

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.
 

Ask a Question

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

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,744
Messages
2,569,479
Members
44,899
Latest member
RodneyMcAu

Latest Threads

Top