ProblemsModern C++A dictionary that answers both ways
AdvancedModern C++

A dictionary that answers both ways

Context

A bidirectional dictionary: usually you go key to value, sometimes value back to key. Both directions fit one operator[] — the argument type picks the direction. Re-keying through the string side is the tricky part: d["aa"] = 10 must find the entry holding "aa" and replace its key.

Task

Implement Int2StrDict: d[1] = "aa" stores a pair; d["aa"] looks the key up by VALUE; assigning to d["aa"] = 10 re-keys that entry. Plus removal by key (d -= 2) and by value (d - "cc"). The subscript operator works in both directions.

Constraints

  • d[int] = string inserts/updates; values are unique by construction of the tests
  • d[string] reads the key holding that value; d[string] = int re-keys that entry
  • d -= key removes by key; d - value returns a copy with that value removed
  • size() and has(key) expose state for the checks

Before you code

  • How can one class offer operator and operator[](const char*) with different meanings?
  • What must the string-side operator[] return so both reading and assigning work? (a proxy)
  • Which invariant keeps the reverse lookup unambiguous?

Tests

  • #1Both directions of lookup
  • #2Re-keying through the value side
  • #3Removal by key and by value

Hints

Hint 1

Two overloads of operator[] by argument type give the two directions. The string side cannot return int& — return a small proxy.

Hint 2

The proxy needs operator int() for reads and operator=(int) for the re-key: erase the old entry, insert under the new key.

Editorint2str-dict.cpp
Results

Hit Submit (or ⌘/Ctrl + ↵) — test results will show up here.