问题
I need a bidirectional container with non-unique keys or values. multimap doesn't work, because it's unidirectional and boost>::bimap only allows unique keys and values. Any such container in the standard or boost libs? Otherwise: any pointers/articles to implement such a structure would be appreciated. Only up to 100 or so element-pairs are expected. Any help appreciated, thanks, Jeanette
回答1:
Actually boost::bimap does allow non-unique keys:
http://www.boost.org/doc/libs/release/libs/bimap/doc/html/boost_bimap/the_tutorial/differences_with_standard_maps.html
Example:
#include <boost/bimap.hpp>
#include <boost/bimap/multiset_of.hpp>
#include <string>
#include <iostream>
namespace bm = boost::bimaps;
int main()
{
    using mybimap = bm::bimap< bm::multiset_of<std::string>, int >;
    mybimap map;
    map.left.insert( mybimap::left_value_type( "orange", 1 ) );
    map.left.insert( mybimap::left_value_type( "apple", 42 ) );
    map.left.insert( mybimap::left_value_type( "orange", 7 ) );    
    auto rng = map.left.equal_range( "orange" );
    for( auto it = rng.first; it != rng.second; ++it )
        std::cout << it->first << ": " << it->second << "\n";
}
Live Demo:
http://coliru.stacked-crooked.com/a/2efdc80cde5f2933
回答2:
You could use a vector of pairs. If you only have 100 elements, linear search is perfectly adequate for lookup on both pair elements. If you have larger collections, or if you frequently need equal-ranges on either pair element, you can maintain separate index structures.
(This is basically how boost.bimap is implemented anyway.)
来源:https://stackoverflow.com/questions/42356127/seeking-bidirectional-map-with-non-unique-keys-or-values