# transform on valarray

Discussion in 'C++' started by Gary Wessle, Aug 18, 2006.

1. ### Gary WessleGuest

Hi

I have 2 valarray<double> a and b, how can I make a = 1/b, that is
each element of a is 1 / each element of b?

I have been reading around and could not understand how it is done.
let a and b have the same size.
transform(a.begin(), a.end(), &b[0], operation)
or
b = a /=(1);

not sure.

thanks

Gary Wessle, Aug 18, 2006

2. ### Guest

Gary Wessle wrote:
> Hi
>
> I have 2 valarray<double> a and b, how can I make a = 1/b, that is
> each element of a is 1 / each element of b?
>
> I have been reading around and could not understand how it is done.
> let a and b have the same size.
> transform(a.begin(), a.end(), &b[0], operation)
> or
> b = a /=(1);
>
> not sure.
>
> thanks

Well, it is a better idea to switch to vectors - as valarrays don't
have iterators, and thren transform is not usefull. An example then
would be:

#include <iostream>
#include <algorithm>
#include <vector>

double reciproke(const double& d)
{
return 1.0/d;
}

int main()
{
std::vector<double> a(2), b(2);
a[0] = 2.0;
a[1] = 4.0;

std::transform(a.begin(), a.end(), b.begin(), reciproke);

for(std::vector<double>::iterator it = a.begin(); it !=
a.end();++it)
{
std::cout << *it << std::endl;
}

for(std::vector<double>::iterator it = b.begin(); it !=
b.end();++it)
{
std::cout << *it << std::endl;
}

return 0;
}

, Aug 18, 2006

3. ### Pierre Barbier de ReuilleGuest

Gary Wessle wrote:
> Hi
>
> I have 2 valarray<double> a and b, how can I make a = 1/b, that is
> each element of a is 1 / each element of b?
>
> I have been reading around and could not understand how it is done.
> let a and b have the same size.
> transform(a.begin(), a.end(), &b[0], operation)
> or
> b = a /=(1);
>
> not sure.
>
> thanks

And why not simply :

a = 1.0 / b;

??

This operation is defined in the standard ...

Pierre

Pierre Barbier de Reuille, Aug 18, 2006
4. ### Stefan NaeweGuest

Gary Wessle schrieb:
> Hi
>
> I have 2 valarray<double> a and b, how can I make a = 1/b, that is
> each element of a is 1 / each element of b?

What's wrong with

valarray<double> b(2.0, 10);
valarray<double> a(1.0/b);

??

/S
--
Stefan Naewe
stefan_DOT_naewe_AT_atlas_DOT_de

Stefan Naewe, Aug 18, 2006