How do you stop vectors from getting run time errors while using an index?

I know you can do it with an iterator loop, but in this case I need to use an index loop, as as far as I'm aware you can't do '*iterator == *iterator + 1'

However when I run this I get a run time error, I'm presuming it's something to do with the index going beyond the size/scope of the vector?

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
	vector<int> ListofNums{ 7,5,9,4,7,2,0,2 };
	int Dublicates = 0;
	sort(ListofNums.begin(), ListofNums.end());
	
	for (int i = 0; i < ListofNums.size(); i++)
	{
		if (ListofNums[i] == ListofNums[i+1])
		{
			cout << "Dublicate: " << ListofNums[i] << endl;

		}
	}

	cout << "sorted list: ";
	for (auto& x : ListofNums)
		cout << x;

	cout << endl;
	return 0;
}
Line 7: This is going to cause an out of bounds reference when i refers to the last element of the vector (i+1 is out of bounds). Change your for loop to:
 
  for (int i = 0; i < ListofNums.size()-1; i++)

Last edited on
but in this case I need to use an index loop

Why? This can be easily accomplished with a range based loop.

1
2
3
4
5
6
7
8
9
10
11
12
    // A variable to check for duplicates.
    int check = ListofNums[0] - 1;

    for(auto& itr : ListofNums)
    {
        if(itr == check)
        {
            cout << "Duplicate: " << itr << endl;
        }

        check = itr;
    }
If you are going so far as to correct his spelling, why not just assign the vector to a set? ;-)
[edit: mis-typed the container type]
Last edited on
Topic archived. No new replies allowed.