C++11实现map的remove_if功能

2020-04-21  本文已影响0人  一代码宗师
#include <iostream>

namespace stuff {
template<class ContainerT, class BinaryPredicateT>
void remove_if(ContainerT& container, BinaryPredicateT predicate)
{
    for (auto iter = container.begin(); iter != container.end();)
    {
        if (predicate(iter->first, iter->second))
        {
            iter = container.erase(iter);
        }
        else
        {
            ++iter;
        }
    }
}
}

int main()
{
    map<int, int> mp =
            {
                    {2, 30},
                    {1, 40},
                    {3, 60},
                    {80, 50},
                    {5, 50},
                    {9, 50},
                    {11, 96}
            };

    cout << "before remove_if : \n";
    for (auto itr = mp.begin(); itr != mp.end(); ++itr)
    {
        cout << itr->first << '\t' << itr->second << '\n';
    }

    stuff::remove_if(mp, [&](const int& key, int& value)
    {
        if (key>1)
        {
            return true;
        }
        return false;
    });

    cout << "after remove_if : \n";
    for (auto itr = mp.begin(); itr != mp.end(); ++itr)
    {
        cout << itr->first << '\t' << itr->second << '\n';
    }
    return 0;
}
上一篇下一篇

猜你喜欢

热点阅读