Skip to content

Instantly share code, notes, and snippets.

@ScottHutchinson
Created November 13, 2019 23:29
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ScottHutchinson/e63d19b60445db4e91669a198817f066 to your computer and use it in GitHub Desktop.
Save ScottHutchinson/e63d19b60445db4e91669a198817f066 to your computer and use it in GitHub Desktop.
BiMap
#include <map>
using std::map;
/* This is a two-way (or bi-directional) map similar to the Boost bimap.
It enables a caller to look up value by key, or a key by value,
which makes it easy to translate to/from a pair of types.
For instance, we can retrieve the name of an enumerator or integer value
and translate it into an integer; and then to update it, we translate it
from integer back into its name to store in the config file.
See https://www.boost.org/doc/libs/1_67_0/libs/bimap/doc/html/boost_bimap/one_minute_tutorial.html
*/
template<typename X, typename Y> struct BiMap {
map<X, Y> m_xy_map;
map<Y, X> m_yx_map;
void Insert(X const& key, Y const& value);
Y GetValue(X const& key);
X GetKey(Y const& value);
};
template<typename X, typename Y>
inline void BiMap<X, Y>::Insert(X const& key, Y const& value) {
m_xy_map.insert({ key, value });
m_yx_map.insert({ value, key });
}
template<typename X, typename Y>
inline Y BiMap<X, Y>::GetValue(X const& key) {
return m_xy_map[key];
}
template<typename X, typename Y>
inline X BiMap<X, Y>::GetKey(Y const& value) {
return m_yx_map[value];
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment