美文网首页
C++11实现map的remove_if功能

C++11实现map的remove_if功能

作者: 一代码宗师 | 来源:发表于2020-04-21 15:01 被阅读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;
    }
    

    相关文章

      网友评论

          本文标题:C++11实现map的remove_if功能

          本文链接:https://www.haomeiwen.com/subject/lmiuihtx.html