arrays

Hello all,
I have more arrays like A1[3],A2[5],A3[10],... .
I want to call them one by one to sum their elements.
How can I do this using a loop?
Thanks
Lets start simple. If you have just one array, how would you sum its elements?
int length=sizeof(A1)/sizeof(*A1);
cout << "Length of array = " << length << endl;
valarray<double> myvalarray (A1,length);
double sum=myvalarray.sum();
length should be redundant. Either you did this:

type arr[size]; //length = size
or this
type * arry = new type(size); //length = size

you shouldnt need to compute it.

you should be able to sum in a loop faster than you can copy the data to a valarray. Could test this I suppose, but I would bet a dumb loop is faster.
for( i = ... length)
sum+= arr[i];

better, put it in a valarray to begin with and forget the array?


now for the original question...

a quick type..
struct loopstruct
{
int length;
type * p;
};

loopstruct ls[numberarrs]; //vector here, push back, is better.
ls[0].length = A1_length;
ls[0].p = A1;
... etc

then loop over that and call the sum loop as a function...

and that is much shorter and simpler if you just use valarray from the get-go, make a vector of valarray to loop over....

Last edited on
Note: Nicolai M. Josuttis writes in his book The C++ Standard Library, chapter 17.4:
The valarray classes were not designed very well. In fact, nobody tried to determine whether the final specification worked. This happened because nobody felt “responsible” for these classes. The people who introduced valarrays to the C++ standard library left the committee long before the standard was finished. As a consequence, valarrays are rarely used.


You could look at http://www.cplusplus.com/reference/numeric/accumulate/ too, but how about an old-fashioned loop to sum one array? Can you show us one?
Topic archived. No new replies allowed.