Problem G: STL——整理唱片(list的使用)

#include<iostream>
#include<list>
#include<iterator>
#include<algorithm>
using namespace std;
list<int> p;
int ii, jj;
bool op(int x)      /*这个很重要*/
{
    return x <= ii;
}
int main()
{
    int n;
    while(cin >> n)
    {
        for(int i = 0; i < n; i++)
        {
            int t;
            cin >> t;
            p.push_back(t);
        }
        int m;
        cin >> m;
        for(int i = 0; i < m; i++)
        {
            int t;
            cin >> t;
            switch (t)
            {
                case 1:
                {
                    cin >> ii >> jj;
                    list<int>::iterator it = find(p.begin(), p.end(), ii);
                    if(it != p.end())
                        p.insert(++it, jj);
                    break;
                }
                case 2:
                {
                    cin >> ii;
                    p.remove_if(op);
 
 
//                    list<int>::iterator it = find(p.begin(), p.end(), ii);
//                    for(int i = ii; i >= 0; i--)
//                        p.remove(i);
 
                    break;
                }
                case 3:
                {
                    cin >> ii >> jj;
                    list<int>::iterator iit = find(p.begin(), p.end(), jj);
                    if(iit != p.end())      /*依据题目上的“注”*/
                        p.remove(ii);
                    list<int>::iterator it = find(p.begin(), p.end(), jj);
                    if(it != p.end())
                        p.insert(++it, ii);
                    break;
                }
 
            }
        }
 
        cout << p.front();
        p.pop_front();
        while(!p.empty())
        {
            cout << " " << p.front();
            p.pop_front();
        }
        cout << endl;
    }
    return 0;
}

这里用到了remove_if(op), 不得不说,这个很好用,意思是list中满足op这个条件的元素将会被全部移除

原文地址:https://www.cnblogs.com/KeepZ/p/11143772.html