ONJava.com -- The Independent Source for Enterprise Java
oreilly.comSafari Books Online.Conferences.


AddThis Social Bookmark Button
  What Is an Iterator in C++, Part 1
Subject:   error in text
Date:   2007-08-14 10:23:16
From:   pvh513
IMO there is an error in the following example posted on http://www.oreillynet.com/pub/a/network/2005/10/18/what-is-iterator-in-c-plus-plus.html?page=4 :

vector<string> v;
// Fill up v with some data
vector<string>::iterator p = v.begin();
p += 5; // Now p refers to the 5th element
p[5]; // Now p refers to the 10th element
p -= 10; // Back to the beginning...

p[5] will return the 10th element (which is not used), but p itself will still refer to the 5th element after doing this. Hence the subsequent statement "p -= 10" is a bug: p will point before v.begin(). I verified this by running a simple test program compiled with g++ 4.2.1 through valgrind. It did report an access violation when dereferencing p after the last statement.

1 to 2 of 2
  1. error in text
    2010-01-03 23:18:43  Cleiton (Brazil) [View]

  2. error in text
    2008-05-16 09:23:22  Steven T [View]

1 to 2 of 2