如何从地图中删除元素

时间:2017-09-15 11:38:43

标签: c++ containers

我想删除一些满足条件的地图元素。我确实找到了解决方案,但我不知道如何使用它。

我有:

std::map<char,int> first;
first['a']=10;
first['b']=60;
first['c']=50;
first['d']=70;

给出的解决方案是:

namespace stuff {
    template< typename ContainerT, typename PredicateT >
    void erase_if( ContainerT& items, const PredicateT& predicate ) {
        for( auto it = items.begin(); it != items.end(); ) {
            if( predicate(*it) ) it = items.erase(it);
            else ++it;
        }
    };
}

我需要的是如何使用此功能删除编号<= 50:

的元素
using stuff::erase_if;
int test_value = 50;  // or use whatever appropriate type and value
erase_if(container, [&test_value]( item_type& item ) {
    return item.property <= test_value;  // or whatever appropriate test
});

2 个答案:

答案 0 :(得分:4)

为什么不使用std::map::erase?如在

first.erase(first.begin());

这将从地图中删除“第一个”项目。

如果你想删除一个特定的密钥,那么它就是一样的:

first.erase('a');

答案 1 :(得分:1)

你的问题在于

中的lambda
erase_if(container, [&test_value]( item_type& item ) {
    return item.property <= test_value;  // or whatever appropriate test
});

您有item_type& itemitem.property这不是您想要的。当您取消引用地图迭代器时,您将获得std::pair<const key_type, T>,这就是lambda需要采取的内容。我们可以使用

erase_if(container, [&test_value]( const std::map<char,int>::value_type& item ) {
    return item.second <= test_value;
});

但这意味着如果我们更改地图以使用其他键,我们需要更改item的类型。为了避免这种情况,我们可以使用auto之类的

来使用通用lambda
erase_if(container, [&test_value]( const auto& item ) {
    return item.second <= test_value;
});