transform on valarray

G

Gary Wessle

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
 
W

wittempj

Gary said:
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;
}
 
P

Pierre Barbier de Reuille

Gary said:
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
 
S

Stefan Naewe

Gary said:
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
 

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

Similar Threads


Members online

Forum statistics

Threads
473,769
Messages
2,569,580
Members
45,054
Latest member
TrimKetoBoost

Latest Threads

Top