iterator out of bounds

this is the code I had before but lost some points due to the out of bounds error for the while loop condition
(*it == *(it + 1)).

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
  void printCommonWords1(string& filename, int threshold) {
	// your code here

	// you MUST use ONLY ONE VECTOR OF STRING (NO STRUCTS) to store the data, and NO MAP OR ANYTHING ELSE.

	// you MUST use ITERATORS to access the data in the vector and NOT [index] NOTATION

	// to print any values call the function above

	int count;
	string word;
	vector<string> words;
	vector<string>::iterator it;
	vector<string>::iterator currentWord;
	ifstream myFile(filename);

	if (!myFile)
		cout << "Couldn't open the file" << endl;

	while (myFile >> word)     //get words one by one (ignoring white spaces) and push them into the string vector
	{
		transform(word.begin(), word.end(), word.begin(), ::tolower);
		words.push_back(word);
	}

	std::sort(words.begin(), words.end());     //sort the vector to make repetitions appear next to each other

	it = words.begin();
	while (it != words.end()) 
	{
		currentWord = it;
		count = 0;
		while (*it == *(it + 1))     //is the current word being looked at the same as the next word?
		{
			count++;
			it++;
		}
		count++;
		it++;
		printIf(*currentWord, count, threshold);
	}
	myFile.close();
}


is changing the while loop condition to (it <= words.end()----) the right way to handle this? I have to use iterators btw.
Last edited on
no, that would be incorrect.
you are accepting `it' to be the end iterator or one less than it.
if `it' is the end iterator, then *it would be invalid.
if `it' is one less than the end iterator, then `it+1' would be the end iterator and so *(it+1) is invalid.

Also, you should check for validity before trying to dereference.


By the way, http://www.cplusplus.com/reference/algorithm/equal_range/
It would probably be better as: while( *(it + 1) != words.end() && *it == *(it + 1))

Check for possible out of bounds access first, then if that fails you won't try to access the container out of bounds in the second check.

thank you. I think you meant while( (it + 1) != words.end() && *it == *(it + 1))
right?
Probably, did you try it? Your compiler will know.

yes I did. words.end() returns an iterator so it won't be correct to compare a dereferenced iterator to that.
Topic archived. No new replies allowed.