STL映射到通用向量C++

Mat*_*der 6 c++ stl

我想实现一个映射,它将字符串映射到通用向量.

我想做这个:

std::map<std::string, std::vector<class T> > myMap;
Run Code Online (Sandbox Code Playgroud)

假设建议的myMap插入了以下内容,它可以这样使用:

vector<int> intVec = myMap["ListOfInts"]; // Works because "ListOfInts" maps to a vector<int>
vector<string> stringVec = myMap["ListOfStrings"]; // Works because "ListOfInts" maps to a vector<string>
Run Code Online (Sandbox Code Playgroud)

当我使用上述语法声明地图时,编译器会发生心脏病发作.

任何人都可以提出任何建议吗?或者是C++中更好的关联数组选项(建议在提升之前不加速).

Chr*_*ger 2

由于您在编写代码时知道所需的类型,因此我建议采用这种方法(未经测试):

// base class for any kind of map
class BaseMap {
 public:
  virtual ~BaseMap() {}
}; 

// actual map of vector<T>
template<typename T>
class MapT : public BaseMap, public std::map<std::string, std::vector<T>> {};

class MultiMap {
 public:
   template<typename T> 
   std::vector<T>& get(const std::string& key) {
     std::unique_ptr<BaseMap>& ptr = maps_[std::type_index(typeid(T))];
     if (!ptr) ptr.reset(new MapT<T>());
     return ptr->second[key];
   }
 private:
   std::map<std::type_index, std::unique_ptr<BaseMap>> maps_;
}

int main() {
  MultiMap map;
  std::vector<int>& intVec = map.get<int>("ListOfInts");
  std::vector<std::string>& stringVec = map.get<std::string>("ListOfStrings");
}
Run Code Online (Sandbox Code Playgroud)