Deleting in a vector

I created a very basic program which contains a vector (my vector) that holds 0, 1 and 1. This program compares each element in the vector. If the element after the one currently being compared is equal to it, it outputs "repeat found!" Now this all works perfectly, but my next step was to erase the repeated one. Everything was working up until the delete step. I get a weird error that says "vector iterator not dereferencable" Thanks if you can help.

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
  // vector::begin/end
#include <iostream>
#include <vector>

using namespace std;

int main ()
{
  vector<int> myvector;
  myvector.push_back(0);
  myvector.push_back(1);
  myvector.push_back(1);



  cout << "myvector contains:" << endl;
  int x = 0;
  for (vector<int>::iterator i = myvector.begin(); i != (myvector.end()-1); ++i, ++x) {
	  
	  cout << *i;

	  if (*i == (myvector.at(x+1))) {
		  cout << " Repeat found!\n";
		  myvector.erase (myvector.begin()+(x+1));
	  }
	  
}
  cout << "\n First 3:" << myvector.at(0) << " " << myvector.at(1) << " " << myvector.at(2) ;
  cout << '\n';

  return 0;
}
myvector.erase invalidates the iterator i.

Btw, if you reach line 28 after deleting one of your 3 elements, you're going to end up with an uncaught exception.

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
#include <iostream>
#include <vector>

using namespace std;

int main()
{
    vector<int> myvector;
    myvector.push_back(0);
    myvector.push_back(1);
    myvector.push_back(1);


    cout << "myvector contains:" << endl;
    int x = 0;

    std::vector<int>::iterator it = myvector.begin();

    int lastValue = *it++;
    std::cout << lastValue << '\n';

    while (it != myvector.end())
    {
        std::cout << *it << '\n';

        if (*it == lastValue)
        {
            std::cout << "Repeat found!\n";
            it = myvector.erase(it);
        }
        else
            lastValue = *it++;
    }

    for (unsigned i = 0; i < myvector.size(); ++i)
        std::cout << i << ": " << myvector[i] << '\n';

    return 0;
}
Topic archived. No new replies allowed.