Vector subscript out of range

I have googled the issue and I do not see why in my program this error is being thrown. Any help would be appreciated.

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
47
48
49
50
51
#include <iostream>
#include <vector>
#include <iterator>
#include <algorithm>
#include <fstream>
#include <string>
#include <cctype>

using namespace std;

int main() {

	int digit = 1;
	string filename;
	//cout for getting user path
	//the compiler parses string literals differently so use a double backslash or a forward slash
	cout << "Enter the path of the data file, be sure to include extension." << endl;
	cout << "You can use either of the following:" << endl;
	cout << "A forwardslash or double backslash to separate each directory." << endl;
	getline(cin, filename);

	//gets file
	ifstream infile{filename};
	istream_iterator<int> infile_begin{ infile };
	istream_iterator<int> eof{};
	vector<int> file{ infile_begin, eof };

	for (int i = 0; i < file.size(); i++) { //file finds lone zeros and removes them
		if (file[i] == 0) {
			file.erase(file.begin() + i);
		}
	}
	for (int i = 0; i < file.size(); i++) { //gets firs digit of each int in vector[i]
			while (file[i] >= 10) {
				file[i] /= 10;
			}
	}
	vector<int> count(9);
	for (int i = 0; i < file.size(); i++) { //loops through file until end
		if (file[i] == i) { //boolean if [i] == i ex. 0 == 0
			count[i+1] = count[i+1] + 1; //increments count 
		}
	}
	cout << "Digit Count Frequency" << endl;
	for (int p = 1; p < 10; p++) {
		//trying to output count[p + 1]
		cout << "  " << digit << "     " << count[p + 1] << endl;
		digit++;
	}	
	system("pause");
}


Last edited on
1
2
3
for (int p = 1; p < 10; p++) {
		//trying to output count[p + 1]
		cout << "  " << digit << "     " << count[p + 1] << endl;


Took me 30 seconds with debugging to find the problem. Your vector "count" is of size 9. And here you are clearly accessing it outside of that. When p is 8 for example, you access it as count[8 + 1] which doesnt exist, since its the index starts at 0, so its from 0-8.
Oh wow that was easy... I knew it was going out but I just didn't put it together where and why. Thank you.
Topic archived. No new replies allowed.