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.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
#include <iostream>
#include <vector>
#include <numeric>

using namespace std;

double sd (vector<double> v2);
double mean(const vector<double>& v1);

int main()
{
vector <double> 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<double>& 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<double> 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.