Vector problems

I am trying to obtain a value and store it in a vector.

An error is returned "vector subscript out of range"

I have omitted most of my code, to narrow in on the area that is presenting the problem. Hopefully, nothing of importance is missing. The code compiles, but gives the error during run time.

Can anyone offer some suggestions?

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

double getDouble(string); // passes a string prompt - returns double
void read(istream & , vector <string> & ); // reads from file

ifstream inStream;

void main()
{
vector <string> names;
vector <double> scores;
size_t count;

read(inStream, names);	

   for (count = 0  ; count <= names.size() ; count ++)
   {
     // this line fails execution after returning from getDouble()
	scores[count] = getDouble(names[count]); 
   }
}

void read(istream & in, vector <string> & theVector )
{
	string inputValue;
	
	for(;;)
	{
		in >> inputValue;
		if ( in.eof() ) break;
		theVector.push_back(inputValue);
	}
}

double getDouble(string a)
{
	double number;
	cout << a << "\t";
	cin >> number;
	return number;
}


Vectors are zero based, so when your for loop gets to .size(), it is out of range. Just change it to < names.size();
Thanks but, no luck. I am still getting the same error.
Your vector has no elements in it. operator[] does not create elements. You need to do one of two things:

1) preallocate the elements in the vector using vector<>::resize(), or
2) use vector<>::push_back() to insert elements rather than [].

Thank you. That fixed the problem, and now helps me to figure out the next.

I'm used to C arrays. The vector class has me all messed up!
Topic archived. No new replies allowed.