1

If I run following C++11 example in Linux (Debian 7, GCC 4.8.2, Eclipse CDT), the while cycle is infinite. First loop is correct. Iterator is decremented by 1 and it references to the first map element. But second and other loops are incorrect. Decrement operator doesn't decrement iterator. It still references to the first element. If I remove comment (in map initialization), while cycle will stop. Could you please tell me, what I did wrong? Thank you very much for every comment.

#include <iostream>
#include <map>
using namespace std;

int main() {
    std::map<int, int> mymap = {{1, 100}, {2, 200}/*, {3, 300}*/};
    auto it = mymap.lower_bound(2);
    cout << "mymap key: " << it->first << endl;
    while(--it != buff.end())
        cout << "mymap key: " << it->first << endl;

    return 0;
}

Note: This code works correct under Windows platform (Visual studio 2013 Express).

  • --begin() is undefined behaviour. Please read http://stackoverflow.com/questions/19417171/stl-iterator-before-stdmapbegin – totoro Apr 04 '14 at 13:34
  • 2
    why are you trying to reach the end() of the map decrementing the iterator in the while loop? Misterious things you will find in that way – hidrargyro Apr 04 '14 at 14:17

1 Answers1

2

You pass a begin() iterator to this line:

while(--it != buff.end())

And --begin() yields undefined behaviour.

Sergey K.
  • 24,894
  • 13
  • 106
  • 174