Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

STL map to generic vector C++

Tags:

c++

stl

I want to implement a map, which maps a string to a generic vector.

I want to do this:

std::map<std::string, std::vector<class T> > myMap;

Assuming the proposed myMap had the following inserted into it, it could be used as such:

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>

When I declare the map with the above syntax the compiler has a heart attack.

Can anybody make any suggestions? Or a better associate array option in C++ (suggest non-boost before boost).

like image 486
Matt Goyder Avatar asked Sep 18 '15 00:09

Matt Goyder


1 Answers

Since you know the type you want when you are writing your code, I propose this approach (untested):

// 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");
}
like image 153
ChronoTrigger Avatar answered Oct 04 '22 12:10

ChronoTrigger