Блог пользователя Night_Lord

Автор Night_Lord, история, 4 года назад, По-английски

I was lately trying to access every 2nd last element from a multiset container. Here I want to first print every 2nd last element from the container then erase it from the container. This process continues until the size of the container reaches to 1.

My so far approach for this process is given bellow-

    int n;cin>>n;
    multiset<int>st;
    for(int i=0;i<n;++i)
    {
        int x;cin>>x;st.insert(x);
    }
    while(st.size()!=1)
    {
        auto it=st.rbegin();
        prev(it,1);
        cout<<*it<<" ";
        st.erase(*it);
    } 

Here, my expected results for the given case is-

6
0 0 1 0 1 1

ans- 1 1 0 0 0

Thanks in advance.

  • Проголосовать: нравится
  • +1
  • Проголосовать: не нравится

»
4 года назад, # |
  Проголосовать: нравится +28 Проголосовать: не нравится

Hi! When you use st.erase(*it), you erased all copies of *it. To avoid this use st.erase(st.find(*it))

»
4 года назад, # |
Rev. 3   Проголосовать: нравится +3 Проголосовать: не нравится

std::prev(itr, n) returns the iterator after you move itr backwards n times. Both std::prev and std::next doesn't actually change the iterator that you pass through as argument. You will need to use std::advance for that, or you can write itr = std::prev(itr, 1).

auto itr = st.rbegin();
std::next(itr);
// itr == st.rbegin();
std::advance(itr, 2);
// itr == next(itr, 2);

And note that you are using reverse iterator on your code (the direction is also reversed), so you should use std::next instead of std::prev if you want the 2nd last element in the multiset.

std::prev
std::advance