Search code examples
gcciteratorfreezelibstdc++postfix-operator

libstd++ postfix operator hangs


Following program hangs. I know, several ways to fix it by changing the code.

// How to compile
//  % g++ <filename>.cpp

#include <iostream>
#include <set>

using namespace std;
int main()
{
    set<int> empty;
    set<int>::iterator iter = empty.begin() ;
    while (iter++ != empty.end())
    {
        cout << *iter << "\n";
    }
    return 0;
}

My questions are:

  1. how to fix it or workaround this piece of code?
  2. is it a bug in libstdc++ or gcc?

thank you in advance for the answers.


Solution

  • iter already points to the end of the set. Incrementing it further with iter++ is not allowed. The workaround is to write a loop that can deal with an empty range:

    for (auto &it : empty)
    for (; iter != empty.end(); ++iter)