Logo

Programming-Idioms

  • Ada
  • JS
  • Fortran
  • Pascal

Idiom #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.

uses classes;
for i := m.count-1 downto 0 do
  if not p(m.items[i]) then m.delete(i);

Filtering is in-place.
  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

p(a) is an elemental function returning a LOGICAL value
for (auto it = m.begin(); it != m.end();) {
  if (!p(it->second)) {
    it = m.erase(it);
  } else {
    ++it;
  }
}

Filters in place.

New implementation...
< >
programming-idioms.org