Supose i have
(A,B)
(A,C)
(A,D)
(B,C)
(B,D)
(C,D)
(D,E)
in a text file. I’ll extract it using regular expressions.
I would like to insert the data in to a container so that it looks like this.
A->B,C,D
B->C,D
C->D
D->E
Which container do I use?
I need to be able to look up data on both the left hand and right hand side of the container, i.e. by key an value. So I need to be able to search/lookup
A,B,C,D in
A->B,C
B->C,D
C->D
D->E
and the B,C in
A->B,C
std::multimap comes to mind… Is basically a map, but allows duplicates in the map key (i.e. you can have multiple “A” keys, each mapping to a “B”, “C” or “D” key, to continue your example).
EDIT: In response to Chris’ comment: you insert items into a multimap in the same manner as a map – you make a
std::pairobject containing the key and value, theninsertthat into the multimap:Assuming here that you literally are examining characters, and
A,B,Cetc aren’t stand-ins for something else. If they are stand-ins, adjust as appropriate.You can then query the multimap for all values under the key ‘A’ as follows:
multimap.equal_rangereturns apaircontaining iterators to the first entry matching the key, and the entry immediately following the last entry matching the key. Therefore, these can be used to iterate over the entries, as demonstrated.EDIT 2 just realised what you really meant by your comment. Multimap does not natively support bidirectional operation (i.e. lookup on value as well as on key), so you might then need to maintain two multimaps – one for each direction. This can be a pain to do though – it can be tricky ensuring that the two remain properly synchronised.
Alternatively, I’m sure there’s some Boost class that would serve the purpose (I don’t actually know – I don’t use Boost myself, but I’m sure someone else should be able to provide more detail).