Logo

Programming-Idioms

# 280 Filter map
Remove all the elements from the map m that don't satisfy the predicate p.
Keep all the elements that do satisfy p.

Explain if the filtering happens in-place, i.e. if m is reused or if a new map is created.
Implementation
C++

Implementation edit is for fixing errors and enhancing with metadata. Please do not replace the code below with a different implementation.

Instead of changing the code of the snippet, consider creating another C++ implementation.

Be concise.

Be useful.

All contributions dictatorially edited by webmasters to match personal tastes.

Please do not paste any copyright violating material.

Please try to avoid dependencies to third-party libraries and frameworks.

Other implementations
for k, v := range m {
	if !p(v) {
		delete(m, k)
	}
}
m = {k:v for k, v in m.items() if p(v)}
for k in list(m):
    if p(m[k]): m.pop(k)
m.select{|k,v| p(v) }
uses classes;
for i := m.count-1 downto 0 do
  if not p(m.items[i]) then m.delete(i);
  real, dimension(:), allocatable :: a
  a = pack(a,p(a))
!
  elemental logical function p(x)
    real, intent(in) :: x
    p = x > 0.7
  end function p

m.retain(|_, &mut v| p(v));
import "maps"
maps.DeleteFunc(m, func(k K, v V) bool {
	return !p(v)
})
$p = sub { $_[0] };

while ( ($k,$v) = each %m ) {
    $f{$k} = $v if $p->($v);
}

%m = %f;
$p = sub { $_[0] };

foreach $k (keys %m) {
    delete $m{$k} if not $p->( $m{$k} );            
}