2013-11-14 75 views
0

所以我一直在搜索C++论坛,并没有真正找到解决方案。我正在尝试创建一个扩展哈希表,其中包含以下详细信息: 可以存储real或string的值。 能够存储真实或字符串的键。 能够存储每个键的多个条目(值)。扩展哈希表

一个例子的外观的结果的:

键: “键” - >值:0,5, “45”, “66”。

key:55 - > value:“Yo”,27,“67”,88。

正如你所看到的,我正在创建一个hashmap,我可以将key存储为real或string +能够将多个key存储为real或每个key的字符串。

+1

['std :: unordered_multimap'](http://en.cppreference.com/w/cpp/container/unordered_multimap)? –

回答

0

由于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[]返回哪些内容需要密钥,并在给定密钥有多个值时返回值。我没有想过这么多,但是我认为它可以返回一个迭代器,它可以用来遍历键的值。

+0

好吧,增加需要很长时间才能安装。所以我会在一切完成时尝试一下。至于地图的想法,我会研究,因为我目前不知道那里发生了什么。下来做一些研究。 – FatalSleep

0

如果您对促进过敏不敏感,您可能需要查看boost::variant。您可以使用boost::variant<double, std::string>作为散列多图中的键和值类型,也可以使用std::vector<boost::variant<double, std::string>>作为散列表中的值类型。

在它的其他优点(如类型安全),一个boost::variant类型是哈希的,只要它的所有成员类型都是可哈希(两者doublestd::string是),所以你应该能够使用它们作为键一个哈希表。