Skip navigation

Expression: vector iterator not dereferencable

A common problem C++ newbs encounter is

Expression: vector iterator not dereferencable

The deal with this statement is it usually occurs in a program like

#include <iostream>
#include <vector>
#include <deque>
using namespace std ;

int main()
{
  vector<int> a ;

  for( int i = 0 ; i < 10; i++ )
    a.push_back( i );

  for( vector<int>::iterator i = a.begin() ; i != a.end() ; ++i )
  {
    if( *i == 5 )
      a.erase( i ) ; // ERROR!!

    cout << *i << endl ;
  }
}

So on the line that says // ERROR!! is where the source of the problem is.

When you .erase from a std::vector, you actually invalidate all existing iterators. So doing ++i then, once you hit the loop repeat, is invalid now.

To fix this, simply UPDATE i AFTER YOU CALL ERASE like so:

      i = a.erase( i ) ;

What this does is SET i TO BEING THE ELEMENT AFTER THE ONE YOU JUST DELETED. The result is the program works and you don’t get the error.

Full program:

#include <iostream>
#include <vector>
#include <deque>
using namespace std ;

int main()
{
  vector<int> a ;

  for( int i = 0 ; i < 10; i++ )
    a.push_back( i );

  for( vector<int>::iterator i = a.begin() ; i != a.end() ; ++i )
  {
    if( *i == 5 )
      i = a.erase( i ) ; // Better!!

    cout << *i << endl ;
  }
}
Advertisements

2 Comments

    • Anonymous
    • Posted October 30, 2011 at 7:21 pm
    • Permalink

    Awesome, your the shit, I looked all over for this 4 hours of mucking with code, Thank You!

  1. yes but not enough ( if last item erased erase returns a next item! then incrimenting at loop rises a error )
    add this line after erase
    if ( i != a.begin() ) i–;


Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: