可以使用C++ STL库中的unordered_map来实现通用的多维映射类型。具体实现方式如下:
#include
#include
template
struct MultiDimMap {
std::unordered_map values;
std::vector> children;
T& operator[](const std::vector& indices) {
if (indices.empty()) {
throw std::out_of_range("Indices cannot be empty.");
}
int index = indices[0];
if (indices.size() == 1) {
return values[index];
}
if (index >= children.size()) {
children.resize(index + 1);
}
return children[index][std::vector(indices.begin() + 1, indices.end())];
}
};
上述代码使用模板类MultiDimMap来实现多维映射类型。在MultiDimMap类中,使用unordered_map来存储一维数据;使用vector和递归调用来支持多维数据。
通过重载[]运算符,可以用多维索引访问多维映射数据。在这里,operator[]函数使用std::vector
使用示例:
MultiDimMap myMap;
myMap[{0, 1}] = 3.1416;
myMap[{0, 1, 2}] = 2.7182;
myMap[{1, 2, 3, 4}] = 1.4142;
此时,myMap对象中存储了三条数据,分别是{0, 1}对应的3.1416,{0, 1, 2}对应的2.7182和{1, 2, 3, 4}对应的1.4142。可以看到,MultiDimMap类支持任意维度的存储,并且可以通过多维索引来访问和修改数据。
上一篇:编写一个通用的C语言模式函数