Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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
}
like image 884
Industrial-antidepressant Avatar asked Mar 19 '26 21:03

Industrial-antidepressant


2 Answers

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.

like image 73
hinafu Avatar answered Mar 22 '26 13:03

hinafu


Inside your outer loop you might increment it more than once. Thus, the condition it != mset.end() might never be true, because the end has already been skipped. Incrementing a past-the-end iterator is undefined behavior, meaning it might also fail silently.

A possible solution might be to also check it != mset.end() in the inner for-loop:

for (unsigned i = 0; (i < count) && (it != mset.end()); ++it, ++i)
    error_msg << "\tNum:" << *it << "\n";
like image 30
Björn Pollex Avatar answered Mar 22 '26 12:03

Björn Pollex



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!