Search code examples
c++algorithmmultiset

Why this multiset print code results forever loop?


I want to print out every duplicates from a multiset, but somehow iterators behave strangely for me. How can fix this code? This code results a forever loop, that surprise me.

#include <set>
#include <iostream>
#include <sstream>

static void print_duplicate(const std::multiset<int>& mset)
{
  std::stringstream error_msg;
  for (auto it = mset.begin(); it != mset.end(); ++it)
    {
      unsigned count = mset.count(*it);
      if (count < 2)
        continue;

      error_msg << "Duplicated numbers found:\n";

      for (unsigned i = 0; i < count; ++it, ++i)
        error_msg << "\tNum:" << *it << "\n";
    }

  std::cout << error_msg.str();
}

int main()
{
  std::multiset<int> mset;

  // fill it
  mset.insert(1);
  mset.insert(1);
  mset.insert(1);

  print_duplicate(mset);
}

EDIT I added a --it at he end of the cycle

  for (unsigned i = 0; i < count; ++it, ++i)
    error_msg << "\tNum:" << *it << "\n";
  --it; // this line fix it
}

Solution

  • for (unsigned i = 0; i < count; ++it, ++i) When this loop ends, it will be equal to mset.end() and since you still have the other ++it from the main loop, you are getting something different to mset.end() hence the program never ends.