Let the user assign the size of an vector



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
#include <iostream>
#include "medel.h"
#include <vector>
using namespace std;

int main()
{
	float speedsum;
	int antal = 0;
	vector<float> myVector;
	cout << "Skriv in hur många tal du vill ha in : " << endl;
	cin >> antal;
	myVector.resize(antal);

	for (unsigned int i = 0; i < myVector.size(); i++) {
		cout << "skriv in tal : ";
		int lol = 0;
		cin >> lol;
		myVector.push_back(lol);
		speedsum =+ myVector.at(i);
		cout <<"speedsum : " << speedsum << endl;


	}
	float medelspeed = medel123(speedsum, antal);
	cout << "du har genomsnitshastigheten : " << medelspeed;

	cin.get();








}


I am trying to let the user decide how big the vector should be, but i cant figure out a way to do that. some wierd shit is going on my error is "syntex error ; before namespace missing, when i click it i get into some new file called xmemory? wtf :/
Last edited on
The problem would appear to be in "medel.h".
My header looks like this... but the header has been working before? :S havent changed anyting in there

 
float medel123(int speedsum, int antal)
Okej now it works, apperently i need ; on the header, althou the for loop wont stop and the values wont add up on speedsum? any suggestons to fix that?
Last edited on
Okej now it works, apperently i need ; on the header, althou the for loop wont stop and the values wont add up on speedsum? any suggestons to fix that?

You are looping on the size of the vector, and you are adding a new element to the vector every iteration, thus the loop will never finish (assuming the vector isn't empty.)

1
2
3
4
5
6
7
    for (unsigned int i = 0; i < myVector.size(); i++) {
        cout << "skriv in tal : ";
        cin >> myVector[i];
        speedsum += myVector.at(i);                      // =+ and += are not the same.
        speedsum =+ myVector.at(i);
        cout <<"speedsum : " << speedsum << endl;
    }
Yeah i changed it abit now
1
2
3
4
5
6
7
	for (unsigned int i = 0; i <antal; i++) {
		cout << "skriv in tal : ";
		int lol = 0;
		cin >> lol;
		myVector.push_back(lol);

	}


The loop will stop after the amount i choiced for "antal" and i made a new for loop that will
add the amounts to speedsum. but noting gets added. i get the amount of 0 on my screen :/
1
2
3
4
	for (unsigned int i = 0; i < antal; i++) {
		speedsum += myVector.at(i);
		cout << "speedsum : " << speedsum << endl;
	}


Why does speedsum not get the amount that myVector has at (i)


Did you notice the code I supplied doesn't do a push_back?

push_back modifies the size of the vector and you have already resized it so that there are antal elements.
Sorry missed that one, it all works now as i wanted :) i i thou push_back was like a giver modifier for the elemental...

Thank you so much for clearing this out for me :)
Topic archived. No new replies allowed.