comparing vectors (vector out of range)

Hello there

I have been running to this problem over and over and don't seem to find what should I do. I have two vectors:

1
2
vector<int> vb(5);
vector<int> a(20);


I am trying to compare both vectors and delete the elements from "a" if elements are common. but it gives me the error: "vector subscript out of range"

here is what I am doing:

1
2
3
4
5
6
7
for(int sd = 0; sd < vb.size(); sd++){
  for(int ck = 0; ck < a.size(); ck++){
	
	if(a[ck] == vb[sd]){
	    a.erase(a.begin()+ck);}
   }
}


it runs and give the result that I want, but at the end throws the exception. I thought of trying it with iterators:

1
2
3
4
5
6
7
for(it = vb.begin(); it != vb.end(); it++){
   for(it1 = a.begin(); it1 != a.end(); it1++){

	if(a[*it1] == vb[*it]){
            a.erase(it1);}
   }
}


it doesn't run and throws the same exception.

I really appreciate any help in advance

regards
Misagh
Last edited on
For your second one, vector::erase() invalidates iterators, so it1 will stop being valid when you delete one element. Furthermore, I'm pretty sure you're dereferencing those iterators wrong...

For your first one... I'm missing something obvious here, sorry. Silly day...

-Albatross
Last edited on
Topic archived. No new replies allowed.