Women in Technology

Hear us Roar



Article:
  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.

Full Threads Oldest First

Showing messages 1 through 2 of 2.

  • error in text
    2010-01-03 23:18:43  Cleiton (Brazil) [View]

    I agree too, p[5] should point to 11th element, but not move the pointer.

    In Bjarne´s [C++ Programming language, 3rd edition, paragraph 19.2.1] : "all operations should have the same efect of pointers" and operator[] over a pointer does not moves it.

    translated back to english from my portuguese copy of book
  • error in text
    2008-05-16 09:23:22  Steven T [View]

    Also the comments should be 6th and 11th element, instead of 5th and 10th.