Vector Error
-
I have wrote one program which deletes the elements from first vector 'v1' which are not in another vector 'v3'. At the deleting time i also want to delete that same index element from vector v2. Eg. The 3 value of 'v3' is not present in 'v1', so i want to delete value 3 from 'v1' and value 7 of index 2 (if we consider 0 based index) from 'v2'. But it goes crash at some point. When you see program you get clear with this thing. I am using Microsoft Visual Studio 6.0 editor. The code snippet is as #include "stdafx.h" #include #include #include int main( ) { using namespace std; vector v1,v2,v3; vector ::iterator result; v1.push_back( 1 ); v1.push_back( 2 ); v1.push_back( 3 ); v1.push_back( 4 ); v2.push_back( 7 ); v2.push_back( 7 ); v2.push_back( 7 ); v2.push_back( 7 ); v3.push_back( 1 ); v3.push_back( 2 ); vector ::iterator V1Startitr = v1.begin(); vector ::iterator V1Enditr = v1.end(); vector ::iterator V2Startitr = v2.begin(); vector ::iterator V2Enditr = v2.end(); for(V1Startitr, V2Startitr; V1Startitr != V1Enditr; V1Startitr++,V2Startitr++) { result = find(v3.begin(),v3.end(),*V1Startitr); if(result == v3.end()) { cout<
-
I have wrote one program which deletes the elements from first vector 'v1' which are not in another vector 'v3'. At the deleting time i also want to delete that same index element from vector v2. Eg. The 3 value of 'v3' is not present in 'v1', so i want to delete value 3 from 'v1' and value 7 of index 2 (if we consider 0 based index) from 'v2'. But it goes crash at some point. When you see program you get clear with this thing. I am using Microsoft Visual Studio 6.0 editor. The code snippet is as #include "stdafx.h" #include #include #include int main( ) { using namespace std; vector v1,v2,v3; vector ::iterator result; v1.push_back( 1 ); v1.push_back( 2 ); v1.push_back( 3 ); v1.push_back( 4 ); v2.push_back( 7 ); v2.push_back( 7 ); v2.push_back( 7 ); v2.push_back( 7 ); v3.push_back( 1 ); v3.push_back( 2 ); vector ::iterator V1Startitr = v1.begin(); vector ::iterator V1Enditr = v1.end(); vector ::iterator V2Startitr = v2.begin(); vector ::iterator V2Enditr = v2.end(); for(V1Startitr, V2Startitr; V1Startitr != V1Enditr; V1Startitr++,V2Startitr++) { result = find(v3.begin(),v3.end(),*V1Startitr); if(result == v3.end()) { cout<
You can't erase an element from a vector by using an iterator that you will reuse later (in the for loop). What you have to do, is use the iterator returned by erase instead (but you shouldn't increment it, since it is already pointing to the next element). Here is some pseudo-code:
while(iter!=v1.end())
{
....
if(remove)
{
iter = v1.erase(iter);
}
else
{
iter++;
}
}PS: please use the pre tags to format your code properly when posting snippets of code.
Cédric Moonen Software developer
Charting control [v3.0] OpenGL game tutorial in C++