Friday, August 24, 2012

Visual Studio 2010 C++ set iterator issue | Set data structure in VS2010 - Part II

In the first part of the post we have explained the basics of set iterator & the issue we might face with set iterator in Visual Studio 2010. Now We should focus on the solutions for this kind issues with the bit complex coding like usage with classes. Anyhow it is better to catch up with simple things first then we can dig the things well later.

Let see what make our program  main2.cpp to break  (in last post's)

Problematic Main.cpp

#include <cstdlib>
#include <iostream>
#include <set>

using namespace std;
int main()
{
set<int> setInt;

for(int i=0; i<5; ++i)
 setInt.insert(i);

 for(set<int>::iterator iItr=setInt.begin(); iItr!=setInt.end(); iItr++)
 {
  if((*iItr) == 2)
   setInt.erase(iItr);
 }

 system("pause");
 return 0;
}

Here this code segment try to delete the element from the Integer Set which have the value "2". It will successfully delete the element but just after the deletion the setInt container's order gets affected, iterator iItr is no longer valid for accessing the elements. But iteration process keeps running. It is unnecessary & not acceptable in Visual Studio 2010. So It may link with the arbitrary location and finally give unhandled exception : Access violation run time error.


We can get rid off this issue through the small trick. We know that deletion happens properly that is why Set container is getting affected and it given crashes since we are iterating again.  Therefore if we stop the latter part everything will go in our way. Only one line of shit needed to throw this F__ away from us. When the particular element is found, it gets removed from the setInt. Once we delete the entity, we should come out from the for loop. For this break will do the trick.

Working Code


for(set<int>::iterator iItr=setInt.begin(); iItr!=setInt.end(); iItr++)
{
if((*iItr) == 2)
{
setInt.erase(iItr); 
break;
}
}

This will work perfectly fine, You can ensure by iterating the values again


for(set<int>::iterator itr=setInt.begin();itr!=setInt.end();++itr)
cout<<"Iterator Values:"<<*itr<<endl;


Output

Iterator Values:0
Iterator Values:1
Iterator Values:3
Iterator Values:4

--------------------------------------------------------------------------------------

For Incoming searches
- unhandled exception : Access violation run time error.
- VS 2010 compilation errors
- Visual Studio 2010 Set run time crashing
- VS 2010 set data structure convention change
- VS 2010 set Iterator issue solving