Search code examples
c++stliteratormultiset

Can't understand the problem with iterator?


The problem states that we have to find the min no of students to remove so that the ith student can pass the exam. So I am basically adding the students in a multiset as it stores sorted values and while the sorted sum is greater than required marks we subtract it out and move to the next one.

The problem comes with the input:

3 4 3 9 1 1 9 8 9

with m : required marks to pass being 14

Here at the 6th index of input which is 9 which has not been added to the multiset is being deleted somehow.

The output that i am getiing when running the troubled input:

0 0 0 ;4--;3-- 2 ;9-- 1 ;9-- 1 ;9--;4--;9-- 3 ;9--;9--;9-- 3 ;9--;9--;9--;9-- 4

The values in :""-- contain the *x which being subtracted from sum there is an extra 9 but i don't know how?

multiset<int> st;
    int setsum =0;
    for(int i=0;i<n;i++)
    {
        int sum = setsum+ar[i];
        if((sum)<=m)
        {
            cout<<"0 ";
        }
        else
        {
            //cout<<sum<<"-*";
            int cnt = 0;
            auto x = st.rbegin();
            while(sum>m)
            {
                sum -= *x;
                //cout<<";"<<*x<<"--";
                x--;
                //if(i==3)
                    //cout<<*x<<"++";
                cnt++;
            }
            cout<<" "<<cnt<<" ";
        }
        st.emplace(ar[i]);
        setsum += ar[i];
    }

Solution

  • Probably not the only problems, but I can't help but notice two major bugs in your use of reverse iterators:

    1. You decrement the iterator (--x) instead of incrementing it (++x); the whole point of reverse iterators is that the direction is reversed, so you should be incrementing the iterator to move backwards through st. The only reason you'd use --x is if you had bidirectional iterator and wanted to move opposite the "natural" iteration order (so forward iterators would run backward, and reverse iterators would run forward).
    2. You never check if you've reached the end of st; if you run off the end of st before sum > m (we have no definition of m, and thus no way to tell if this condition is necessarily true prior to running off the end of st), you hit undefined behavior. The simplest fix is to simply update the test to while (sum > m && x != st.rend()), though that may affect your code logic later on (since now exiting the loop isn't a guarantee that sum is less than or equal to m), necessitating further tests.