由于C++是一种静态类型语言,因此您必须为此创建的任何类创建模板,或者必须为该键和值定义特定类型。或者,您可以使用标准模板库中提供的内置map<T>
类型,但是又没有办法在运行时检测map<T>
的模板参数需要使用哪种类型。
尽管如此,您也许可以使用类似双向映射的东西。升压有一个,这里是一个我最近写的代码:
// bimap.h
#pragma once
#include <string>
#include <list>
using namespace std;
template <typename T0, typename T1>
class bimap
{
public:
bimap(){}
bool Insert(T0, T1);
void Clear();
T0& operator[](T1);
T1& operator[](T0);
private:
list<pair<T0, T1>> m_dictionary;
};
template<typename T0, typename T1>
bool bimap<T0, T1>::Insert(T0 key, T1 value)
{
for (list<pair<T0, T1>>::const_iterator cur = m_dictionary.begin(); cur != m_dictionary.end(); cur++)
{
if ((*cur).first == key)
return false;
}
m_dictionary.push_back(make_pair(key, value));
return true;
}
template<typename T0, typename T1>
void bimap<T0, T1>::Clear()
{
m_dictionary.clear();
}
template<typename T0, typename T1>
T0& bimap<T0, T1>::operator[](T1 key)
{
for (list<pair<T0, T1>>::iterator cur = m_dictionary.begin(); cur != m_dictionary.end(); cur++)
{
if ((*cur).second == key)
return (*cur).first;
}
throw new out_of_range("Key does not exist.");
}
template<typename T0, typename T1>
T1& bimap<T0, T1>::operator[](T0 value)
{
for (list<pair<T0, T1>>::iterator cur = m_dictionary.begin(); cur != m_dictionary.end(); cur++)
{
if ((*cur).first == value)
return (*cur).second;
}
throw new out_of_range("Value does not exist.");
}
双向映射的好处是,你可以通过使用值或使用密钥值访问密钥。不利的一面(至少在我的代码中,但是我也可以用boost类来想象),它不允许每个键有多个值。但是修改我的代码并不难。您只需修改Insert()
方法,然后考虑如何从operator[]
返回哪些内容需要密钥,并在给定密钥有多个值时返回值。我没有想过这么多,但是我认为它可以返回一个迭代器,它可以用来遍历键的值。
['std :: unordered_multimap'](http://en.cppreference.com/w/cpp/container/unordered_multimap)? –