STL issues.. (again)..

I don't understand .. why do I keep getting vector subscript errors even after using vector::clear() and vector::resize(size_type n) ?

Here is my code:

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 <vector>
#include <algorithm>
#include <fstream>

using namespace std;

bool compareGreaterThan(int x, int y){
	return (x > y);
}

void readData(vector<int>& v, int n){
	ifstream in("maxsecv.in");
	v.clear();
	v.resize(n);
	int x;
	in >> n;
	while (!in.eof() && in >> x){
		v.push_back(x);
	}
}

void processAndWrite(vector<int> v, int n){
	ofstream out("maxsecv.out");
	int lengthSequenceMax1 = 0, lengthSequenceMax2 = 0, aux = 0;
	vector<int> auxLength; auxLength.clear(); auxLength.resize(n);
	vector<int>::iterator itBegin;
	vector<int>::iterator it;
	itBegin = v.begin();
	for (it = itBegin; it != v.end(); ++it){
		if (*it == 1){
			aux++;
		}
		else{
			auxLength.push_back(aux);
			aux = 0;
		}
	}
	sort(auxLength.begin(),auxLength.end(),compareGreaterThan);
	lengthSequenceMax1 = auxLength.at(1);
	lengthSequenceMax2 = auxLength.at(2);

	out << lengthSequenceMax1 + lengthSequenceMax2;
}

int main(int argc, char *argv[]){
	vector<int> v;
	int n = 0;
	readData(v,n);
	processAndWrite(v,n);
	return 0;
}


The highlighted parts are where I am using the vectors. Could someone explain me why Visual C++ compiler returns vector subscript error ?

PS: The error sent me to
1
2
3
4
5
6
7
//vector.h
//...
	__declspec(noreturn) void _Xran() const
		{	// report an out_of_range error
		_Xout_of_range("invalid vector<T> subscript");
		}
//... 

1
2
3
4
5
6
7
8
//xthrow.h
//...
_CRTIMP2_PURE __declspec(noreturn) void __CLRCALL_PURE_OR_CDECL _Xout_of_range(_In_z_ const char * _Message)
	{ // report an out_of_range error
	_THROW_NCEE(out_of_range, _Message);
	}

//... 



EDIT: Nevermind. Found it. I used
v.clear(); v.resize(n); before reading the n from file.
Last edited on
Topic archived. No new replies allowed.