### Inconsistent output in vector problem

I have written a code to find the standard deviation of all elements in a vector (the first n primes are inputted). Whilst my code always compiles it will crash when certain vector sizes are input. 3 is an example. I cant see why the size of the vector changes anything.

 ``12345678910111213141516171819202122232425262728293031323334353637383940414243444546`` ``````#include #include #include using namespace std; double sd (vector v2); double mean(const vector& v1); int main() { vector primes; // use push back to fill vector with n primes. cout << "The sd of all elements is " << sd( primes ) << endl; return 0; } double mean(const vector& v) { double sum_of_elems=0, mean; sum_of_elems = accumulate(v.begin(),v.end(),0); mean = sum_of_elems / v.size(); return mean; } double sd(vector v) { double sum_of_squares=0, sd; for (int i = 0; i < v.size(); i++) { v[i] = (v[i] - mean (v)); v[i] *= v[i]; } sum_of_squares = accumulate(v.begin(),v.end(),0); sd = sum_of_squares / v.size(); return sd; } ``````

Hints and other help greatly appreciated! Thanks in advance.
Last edited on
 `foo.cpp:26:25: error: ‘mean’ was not declared in this scope`
when asking about code, make sure that the code you posted actually does reproduce your issue.

http://www.cplusplus.com/forum/general/112111/
Last edited on
Sorry, I am new to this forum. I have edited to include the mean function. It now runs but outputs 'nan' as I didnt include the vector filling code to stop the post getting too long. I can if it will help though?
Last edited on
Managed to fix the code by changing it and passing by reference.
Topic archived. No new replies allowed.