I might wonder if I have an int vector like this and I want to achieve the averagevalue for Element 0-8 wich is ((1+2+3+4+5+6+7+8+9) / 9) = 5

What method could be used for this ?

std::vector<int> Number(10);

Number = 1;
Number = 2;
Number = 3;
Number = 4;
Number = 5;
Number = 6;
Number = 7;
Number = 8;
Number = 9;
Number = 10;
Number = 11;

## All 5 Replies

If you have 9 as the number of elements you are interested in for the average, I would set up a sum variable, initialize it to 0, then set up a loop that repeats 9 times. Each trip through the loop would access a different element of the vector (design the loop so that the loop control variable is the index of the element you want). Add the value of that element to the sum variable. After the loop, divide the sum variable by 9.

were you looking for a standard library function?
like std::accumulate ( in header <numeric> )

``````// vec is a std::vector<int> and N <= vec.size()
int sum = std::accumulate( vec.begin(), vec.begin()+N, 0 ) ;
// average == sum / double(N)``````
commented: Useful function. +1
commented: nice one +2

were you looking for a standard library function?
like std::accumulate ( in header <numeric> )

``````// vec is a std::vector<int> and N <= vec.size()
int sum = std::accumulate( vec.begin(), vec.begin()+N, 0 ) ;
// average == sum / double(N)``````