Help with Runtime Error

//v IS A VECTOR
//m IS MAPPING BETWEEN THE ELEMENTS WITH ITS NUMBER OF OCCURRENCES

while (m.size() > 0)
		{
			for (auto &x : m)
			{
				v.push_back(x.first);
				x.second--;
				if (x.second == 0)
					m.erase(x.first);
			}
		}

// This is working fine on my compiler but giving RE on online IDE
//I need to know the problem and the alternative solution. Please help.

There are many technical definitions of RE but i can simply explain you how RE occurs.
RE occurs when for a particular input your code terminates without giving the output (further processes are also terminated).
So, if you want to know why RE is occurring please share the question, so that we can help you to frame edge testcases that may be causing RE.

Found the problem and the alternative. The problem was in the iterator pointing to the element. When the element was deleted, the map structure changed and the iterator pointed nowhere. This could be solved by first storing the iterator position and then reassigning it to the traversing iterator. Below is the working alternative approach.

while (m.size() > 0)
		for (auto it = m.begin(); it != m.end(); )
		{
			int p = it->F;
			v.push_back ( p );
			m[p] = m[p] - 1;
			if (m[p] == 0)
			{
				auto it2 = it;
				it2++;
				m.erase(it);
				it = it2;
			}
			else it++;
		}

While iterating through a set, or a map, you should not erase elements. When an element is erased, the iterator pointing to it becomes void, or not useable. If you want to do so, you have to do something like what you’ve done in the second code. Another way to do this is writing it = m.erase(it) from C++11 (I think), the erase function returns a valid iterator pointing to the next element. You can also do m.erase(it++). This erases it, but as we do an increment, the value of it changes before the element is erased and hence is now a valid iterator. Note the post increment operation which would pass the value of it to erase() first, and then increment it.

Also format your code.

Thanks a lot! For the formatting tip too!

1 Like