【发布时间】:2015-04-17 13:45:38
【问题描述】:
我正在寻找类似 C++ 中“Key to Key”映射的东西。
我的意图如下:
- 每个键 - “左侧”或“右侧”都是唯一的
- 左侧的键可以通过右侧的键查找,反之亦然
作为一个例子,为了让我的意图更清楚,在代码中,它可能看起来像:
key2key<int, string> myMap; // int maps to string, string to int
myMap.insert(0, "zero");
myMap.insert(1, "one");
myMap.insert(2, "two");
myMap.insert(1, "zero"); // would throw an error
myMap.insert(9, "one"); // would throw an error as well
cout << myMap.lookupLeft(1) << endl; // prints "one"
cout << myMap.lookupRight("one") << endl; // prints "1"
当然,我可以继续自己实现类似的东西,但是那里有什么东西吗? 我不想重新发明轮子,所以也许可以修改或重用标准 STL 容器或提升。
为什么我认为它有用?
假设您正在读取一个配置文件,并且您还想对该配置文件进行写入或更改。 此配置文件可能包含一些在 C++ 内部表示为类型安全枚举类的字段。 使用“Key to Key”映射是这些值的非常轻量级的生成器和类型转换器。
enum class DebugLevel {error, warning, debug};
const key2key<DebugLevel, string> debugLevelMap = {
{DebugLevel::error, "error"},
{DebugLevel::warning, "warning"},
{DebugLevel::debug, "debug"},
}
DebugLevel foo = debugLevelMap.lookupRight("error");
string bar = debugLevelMap.lookupLeft(DebugLevel::warning);
【问题讨论】:
-
你可以简单地使用两张地图。如果对象很大,请考虑将它们放在其他地方(例如,在向量中)并且只在地图中存储指针。或者使用共享指针。
-
但这并不妨碍一张地图可能包含两个等价的值。
-
在插入其中任何一个之前,您需要检查两个映射是否已包含键/值。
-
看看 boost.bimap。
标签: c++ c++11 boost stl containers