一对一的映射实际上很容易,最快的方法是维护两个映射,每个方向一个。如果它不是一对一的,它会变得更加复杂,因为您需要提供一种方法来获取值或键的集合,而不是单个的。幸运的是,您只有一对一的要求。
其中一个映射是您现在拥有的映射,另一个会将值映射到给定键,所以两者都是:
std::map<std::string, int> forwardmapobj;
std::map<int, std::string> reversemapobj;
这些将被维护在某种bidimap 类中。
每当您插入或删除bidimap 时,您都必须对两个 内部映射执行等效操作。
例如,这里有一些伪代码。它维护两个映射,并确保它们在您进行的任何更改键和值的操作时保持同步:
class biDiMap:
map<string, int> forwardMap
map<int, string> reverseMap
void add(string key, int val):
if exists forwardMap[key]: throw exception 'duplicate key'
if exists reverseMap[val]: throw exception 'duplicate value'
forwardMapObj[key] = val
reverseMapObj[val] = key
void delKey(string key):
if not exists forwardMap[key]: throw exception 'no such key'
delete reverseMap[forwardMap[key]]
delete forwardMap[key]
void delVal(int val):
if not exists reverseMap[val]: throw exception 'no such value'
delete forwardMap[reverseMap[val]]
delete reverseMap[val]
int getValFor(string key): return forwardMap[key]
string getKeyFor(int val): return reverseMap[val]
显然,您可以添加许多其他内容,但这应该构成基础。无论如何,在将其转换为 C++ 类之前,您可能已经完成了足够的工作:-)
如果您不想要推出自己的解决方案,那么 Boost 有一个非常好的解决方案,您可以按原样使用它。 Boost.Bimap 提供了一个完全模板化的双向地图,您应该能够用最少的代码使用它,例如以下完整的程序:
#include <iostream>
#include <string>
#include <boost/bimap.hpp>
using std::string;
using std::cout;
using std::exception;
using boost::bimap;
int main()
{
typedef bimap<string, int> SiMap;
typedef SiMap::value_type SiEntry;
SiMap bidi;
bidi.insert(SiEntry("ninety-nine", 99));
int i = 0;
for (string str: {"one", "two" , "three", "four", "five", "six"}) {
bidi.insert(SiEntry(str, ++i));
}
cout << "The number of entries is " << bidi.size() << "\n\n";
for (auto i = 1; i <= 7; i += 3) {
try {
cout << "Text for number " << i << " is " << bidi.right.at(i) << "\n";
} catch (exception &e) {
cout << "Got exception looking up number " << i << ": " << e.what() << "\n";
}
}
cout << "\n";
for (auto str: {"five", "ninety-nine", "zero"}) {
try {
cout << "Number for text '" << str << "' is " << bidi.left.at(str) << "\n";
} catch (exception &e) {
cout << "Got exception looking up text '" << str << "': " << e.what() << "\n";
}
}
cout << "\n";
return 0;
}
它在数字的文本形式和整数值之间创建双向映射,然后进行一些查找(在两个方向上)以表明它有效:
The number of entries is 7
Text for number 1 is one
Text for number 4 is four
Got exception looking up number 7: bimap<>: invalid key
Number for text 'five' is 5
Number for text 'ninety-nine' is 99
Got exception looking up text 'zero': bimap<>: invalid key