Problem passing a vector through a function

I'm new to programming, so bear with me. Part of my code requires me to calculate the mean of all the elements of a vector but I am having problems putting my vector into the function 'mean'.

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
#include <iostream>
#include <vector>
#include <numeric>


using namespace std;

double mean(const vector<long>& v);

int main()
{
vector <long> primes;

/*
Fill vector primes with first N primes using push back
*/

//mean
cout << "The mean of all elements is " << mean( primes ) << endl;


    return 0;
}


double mean(const vector<long>& v)
    {
        double sum_of_elems=0, mean;
        sum_of_elems = accumulate(v.begin(),v.end(),0);
        mean = sum_of_elems / v.size();

        return mean;
    }


After messing around with it, this code now runs! Just need to get it to return the value properly.

Any help/advice would be greatly appreciated!
Last edited on
try :

cout << "The mean of all elements is " << mean( primes, primes.size() ) << endl;
Also, at line 12 the declaration should be <long>, not <int>

There's no need to pass size() as a separate parameter, the function has access to v.size() instead.
@Shadow fiend
Still no luck. That was my first thought too. Error output this time:

error: in passing argument 1 of 'int mean(const std::vector<long int>&, int&)'


on line 8.

error: invalid initialization of reference of type 'const std::vector<long int>&'
from expression of type 'std::vector<int>'


on line 19.

@Chervil
Did not see that at all! Ive fixed it and it now runs. Opening post has been updated.

Thank you.
Last edited on
as Chervil says : @line 12 should be : vector <long int> primes;
I don't understand. shadow fiend gave you the answer already ?
(and I pointed out the other error at line 12)
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
#include <iostream>
#include <vector>
#include <numeric>

using namespace std;

int mean(const vector<long>& v);

int main()
{
    vector <long> primes;

    /*
    Fill vector primes with first N primes using push back
    */
    primes.push_back(2);

    //mean
    cout << "The mean of all elements is " << mean(primes) << endl;


    return 0;
}


int mean(const vector<long>& v)
{
    int sum_of_elems=0, mean;
    sum_of_elems = accumulate(v.begin(),v.end(),0);
    mean = sum_of_elems / v.size();

    return mean;
}
Last edited on
Sorry, i didnt update the last reply. It now runs smoothly. Thank you for the help! :)
Last edited on
There may be an integer divide problem. Try changing the definition to
double sum_of_elems, mean;
Topic archived. No new replies allowed.