I need to create a nested map structure of a given depth, in order to keep track of the number of times that a given combination of words occurs in a file
for example if the depth is 3, i should have
map<string, map<string, map<string, int> > > data;
and then be able to say
data["test"]["test"]["test"]++;
i googled around and found a nice recursive templated class for this purpose:
template <int N, typename T, typename X>
class MyMapCreator {
public:
typedef ::std::map<T, typename MyMapCreator<N - 1, T, X>::type> type;
};
template <typename T, typename X>
class MyMapCreator<1, T, X> {
public:
typedef ::std::map<T, X> type;
};
which would then be used like so:
MyMapCreator<4, ::std::string, int>::type myMap;
myMap["a"]["b"]["c"]["d"] = 123;
cout << myMap["a"]["b"]["c"]["d"];
now that structure itself is great and works fine, but since i have a variable depth, i can't hardcode any subscripting on it to access the integer values, which is what i care about. so i need a way to recursively go from nested map to nested map until i get to the integer so i can increment it. here's what i've come up with:
template<class T>
void crawlMap(T & data, int depth)
{
if (depth == 0) data++;
else crawlMap(data["test"], depth-1);
}
now what i was hoping would happen would be that for each recursive call, data would have a new type, but that it would be okay because of the fact that it's templated, and a new version of the function would be created for each successive map type (from map<string, map<string, ... map<string, int> ...> > to the core map<string, int>. it's not working though, and the errors are pretty cryptic. is there an easier way? maybe add a member function to the class? i can't see a good way to do it. thanks for any help you can give!