Annoying Runtime Error With Vectors

closed account (DL30RXSz)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
	
	vector <double>::iterator iPerfectMark = marks.begin();
	while(iPerfectMark != marks.end())
	{
		iPerfectMark = find(iPerfectMark, marks.end(), 83);
		vector <double>::iterator lastCheckedLocation = marks.begin();

		if(iPerfectMark != lastCheckedLocation)
		{
			cout 
			<< * iPerfectMark 
			<< "% at location: "
			<< distance(marks.begin(), iPerfectMark)
			<< endl;
		}

		lastCheckedLocation = iPerfectMark;
		++iPerfectMark;
	}


Obviously I'm searching the vector marks for a percentage of 83. This always gives me a runtime error, though. I don't see how it could try to read/write outside of the vector's memory since the loop won't run if it is at the start or end of the vector.
Last edited on
You are reinitializing lastCheckedLocation, take it out of the loop. What is happening right now is you are setting last checked to always be the beginning. Unless you want to always check against the beginning. What are you trying to do?
Last edited on
You do not have to store the last checked position because you are changing the search range each time. The program is crashing because find will return marks.end() if 83 can not be found and you are still calling cout << * iPerfectMark ...


Try this:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
	vector <double>::iterator iPerfectMark;
        iPerfectMark = find(marks.begin(), marks.end(), 83);
	while(iPerfectMark != marks.end())
	{
		cout 
		<< * iPerfectMark 
		<< "% at location: "
		<< distance(marks.begin(), iPerfectMark)
		<< endl;

                ++iPerfectMark;
                iPerfectMark = find(iPerfectMark, marks.end(), 83);
		
	}
Topic archived. No new replies allowed.