Call functions with vectors

Hello, I am calling a function to do the average of my values...

so the problem is how do i move the vector over to the function? with the values from main? i writted down in comments in the code where i get the errors atm


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

using namespace std;

float medel(int v[], int n) {
	int antal = n;
	int speedsum;
	for (unsigned int i = 0; i < antal; i++) { //for loop tilldelar värdena användare skrivit in till elementena
		speedsum += v.at(i);     // <<< ----- ERROR Must have a class type
		cout << "speedsum : " << speedsum << endl;
	}

	float medel = speedsum / antal;
	return medel;
}


int main() {

	int antal;
	vector<int> myVector;
	cout << "Skriv in hur många tal du vill ha in : " << endl; //låter användare bestämma hur många tal han vill ha in
	cin >> antal;
	myVector.resize(antal); //ändrar storleken på vectorn till "antal"ets storlek

	for (unsigned int i = 0; i <antal; i++) { //for loop som låter användare skriva in värden till elementena
		cout << "skriv in tal : ";
		cin >> myVector[i];
	}

	float medelv = medel(myVector[], antal);  //<<< ---- ERROR Expected a expression


	cout << "Du har medelvärdet : " << medelv;

	cin.get();




}
Anyone that can explain?
On line 10 v is not a vector, so you cannot use its nonexistent vector methods.

On line 32, if you want to use the data you have in a vector to a function taking an array:

float medelv = medel(myVector.data(), myVector.size());

Alternatively, define medel like so:
1
2
3
4
5
6
7
8
9
float medel(const std::vector<int>& v) 
{
    int speedsum = 0;

    for (auto elem : v)
        speedsum += elem;

    return float(speedsum) / v.size();
}


And call it like so:
float medelv = medel(myVector);
Last edited on
it works good now, but i am not sure what the code is really doing?

1
2
3
4
5
6
7
8
9
10
float medel(const std::vector<int>& v) 
{
    int speedsum = 0;

    for (auto elem : v)
        speedsum += elem;

    return float(speedsum) / v.size();
}


Thats an enchanded for loop right? what is Auto elem : v doing??

and float medel(const std::vector<int>& v) why use "&" after the <int>

please explain if u have time, so i learn it ^^
> what is auto elem : v doing??
traverse the vector `v', `elem' will take the value of each element.


> why use "&"
pass by reference. Containers are expensive to copy (you'll need to copy each element).
take vector<int> myVector as a global variable
Topic archived. No new replies allowed.