Logo

Programming-Idioms

This language bar is your friend. Select your favorite languages!

Idiom #354 Increment map entry

Set the value for the key k in the map m to 1 if the entry doesn't exist yet in m, or increment the entry value if it already exists.

m[k]++
m.merge(k, 1, Integer::sum);
fgl
type
  TMap = specialize TFPGMap<string, integer>;

var
  m: TMap;
  key: string;
  idx: integer;


begin
  m := TMap.Create;
  ...
  idx := m.IndexOf(key);
  if (idx >= 0) then
    m.Data[idx] := m.Data[idx] + 1
  else
    m.Add(key,0);
  ...
  m.Free;
m.update(k=m.get('k', 0) + 1)
m[k] = m.fetch(k, 0) + 1

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