Reply appended...

> From: [email protected] [mailto:[EMAIL PROTECTED] On Behalf Of 
> Robert Ryan
> Sent: Saturday, February 03, 2007 7:48 PM
> To: [email protected]
> Subject: Re: [c-prog] what is a vector ?
>
> int array_one[ 25 ];
> > int *array_two = new int[ 25 ];
> 
> if you wanted to total up the ints, how would you do it. 
> for(int i=0; i<array_one; i++) {
> total += array_one [i]; 
> and then cout << "The total Is:  " <<;  }

At least several methods:

1.  Use another variable to store the size of the array:

    const size_t ARY_SIZE = 25;
    int array_one[ARY_SIZE];

    /* set array_one values */

    int total = 0;
    for (size_t n = 0; n < ARY_SIZE; ++n)
    {
        total += array_one[n];
    }


2.  if iteration is at the same level where array_one is defined, you may
also use size_of:

    int array_one[] = { ... }; /* Initialized array.  
                                  array size not explicitly specified */

    int total = 0;
    for (size_t n = 0; n < sizeof array_one; ++n)
    {
        total += array_one[n];
    }


3.  Use std::accumulate() as in Victor's reply.


4.  Use std::vector<> in place of int array:

     std::vector<int> array_one;

     /* put values into array_one via push_back */

4a. For accumulation, use either std::accumulate:

     int total = std::accumulate(array_one.begin(), array_one.end(), 0);

4b. or size() member to get the size of the vector:

        int total = 0;
        for (size_t n = 0; n < array_one.size(); ++n)
        {
            total += array_one[n];
        }



Reply via email to