How to keep from going out of bounds in a vector

I was hoping that someone could help me figure out a basic way to check if a looping element will cause a vector to go out-of-bounds?
I posted the code below which is just a function within a larger program.

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
 //display the x most used words greater than or equal to y letters and their frequencies
void x_most_used_gt_et_letters(vector<string>& words2, vector<int>& frequencies2,
	vector<int>& letter_count,int& max_words, int& max_letters)
{

	for(int i=0; i<letter_count.size(); i++)
	{
		//first find the words greater than or equal to y letters
		if(letter_count.at(i)==max_letters)
		{
			//output only the x most used words 
			for(int j=i; j<i+max_words ;i++)
			{

				if(words2.at(j)== words2.back()+1)
				{
					cout<< words2.at(j)<<" "<< frequencies2.at(j)<<endl;
				}
			}
			//exit the outer (for loop) to avoid repeating the words greater than or equal to y letters
			break;
		}
	}

}
Well, if you setup your for loops correctly and don't delete elements from the vector in the loop then you should never have to worry about it but you could always check if the index is greater than -1 and less than vector.size().
Last edited on
You can also use iterators to traverse the vector. See the example here:
http://www.cplusplus.com/reference/vector/vector/vector/
Topic archived. No new replies allowed.