Reverse_find for maps

Hi, Is there an equivalent to the Reverse_Find operation on map containers ? To find a key starting from an element, or perhaps find the first index/key matching that element. It exists for vectors, but I need to associate a string with each element so maps should be the way to go, even though I have very little experience with data structures.
If there is an atlernative, I listen.

It depends on the type of the map. If using a hashed map, I don’t believe they are stored in a way that allows for in order iteration (generally for all implementations of hash maps). I don’t know that for 100% sure, but that is my initial understanding. Maybe someone with a better understanding of hashed maps will comment if otherwise.

If using an ordered map you can just do a regular iteration loop in reverse:


with Ada.Text_IO; use Ada.Text_IO;
with Ada.Containers.Indefinite_Ordered_Maps;  use Ada.Containers;

procedure jdoodle is
    package Maps is new Indefinite_Ordered_Maps(String, Integer);
    Map : Maps.Map;
    
    Cursor : Maps.Cursor;
begin
    Map.Insert("a", 1);
    Map.Insert("b", 2);
    Map.Insert("c", 3);
    Map.Insert("d", 4);
    Map.Insert("e", 5);
    Map.Insert("f", 6);
    Map.Insert("g", 7);
    
    Cursor := Map.Find("d");
    
    for C in reverse Map.Iterate(Cursor) loop
        Put_Line(Maps.Key(C) & " =>" & Maps.Element(C)'Image);
    end loop;
    
    
end jdoodle;

Output:

d => 4
c => 3
b => 2
a => 1

gcc -c jdoodle.adb
gnatbind -x jdoodle.ali
gnatlink jdoodle.ali -o jdoodle

I saw that we have to use cursor, the same operation (Key) doesn’t exist with Element !
No matter though… I’d iterate and filter the cursor with the matching Map.Key (C). I’ve never used cursors ever before, nor an Iterate function (or procedure, dunno). These kinds of operations are still mysterious, but I suppose I’ll come to them as I go.

Just realized I misunderstood what you were looking for earlier. My apologies

1 Like

I would use a second map where I’d swap the key and element types.
That way, the reverse search will be also conveniently fast on large data.

2 Likes