Blood-HaZaRd
Blood-HaZaRd

Reputation: 2124

How delete elements from map

I want to delete some map elements satisfying a condition. I did find a solution but I did not know how use it.

I have:

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

the solution given is :

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;
        }
    };
}

What I need is how to adopt this function to delete elements having number <= 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
});

Upvotes: 0

Views: 989

Answers (2)

NathanOliver
NathanOliver

Reputation: 180500

Your issue here is with your lambda in

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

You have item_type& item and item.property which is not what you want. When you dereference a map iterator you get a std::pair<const key_type, T> and that is what the lambda needs to take. We could use

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

But this means if we change the map to use some other key we need to change the type of item. To avoid that we can use a generic lambda using auto like

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

Upvotes: 1

Some programmer dude
Some programmer dude

Reputation: 409166

Why not use std::map::erase? As in

first.erase(first.begin());

That will remove the "first" item from the map.

If you want to remove a specific key, then it's just the same:

first.erase('a');

Upvotes: 4

Related Questions