C++ 如何用地图表示三维阵列?
我如何表示像这样的3D阵列C++ 如何用地图表示三维阵列?,c++,C++,我如何表示像这样的3D阵列 myarray[1000][1000][1000]; 这是一个大数组,超出了内存限制。每个单元都不会被使用,因此会造成巨大的内存浪费。我想映射3个数字和值,还有其他方法吗 #include <map> #include <iostream> struct MapIndex{ int x, y, z; MapIndex() :x(0), y(0), z(0){ } MapIndex(int x_, in
myarray[1000][1000][1000];
这是一个大数组,超出了内存限制。每个单元都不会被使用,因此会造成巨大的内存浪费。我想映射3个数字和值,还有其他方法吗
#include <map>
#include <iostream>
struct MapIndex{
int x, y, z;
MapIndex()
:x(0), y(0), z(0){
}
MapIndex(int x_, int y_, int z_)
:x(x_), y(y_), z(z_){
}
};
bool operator<(const MapIndex &v1, const MapIndex &v2){
if (v1.z > v2.z)
return false;
if (v1.z < v2.z)
return true;
if (v1.y > v2.y)
return false;
if (v1.y < v2.y)
return true;
if (v1.x < v2.x)
return true;
return false;
}
template<typename Val> struct Array3D{
typedef std::map<MapIndex, Val> Data;
Data data;
Val defaultValue;
const Val& getValue(int x, int y, int z) const{
MapIndex index(x, y, z);
Data::const_iterator found = data.find(index);
if (found == data.end())
return defaultValue;
return found->second;
}
void setValue(int x, int y, int z, const Val &val){
data.insert(std::make_pair(MapIndex(x, y, z), val));
}
bool hasValue(int x, int y, int z) const{
Data::const_iterator found = data.find(MapIndex(x, y, z));
return found != data.end();
}
Array3D(const Val& defaultValue_ = Val())
:defaultValue(defaultValue_){
}
};
int main(int argc, char** argv){
Array3D<int> ints;
std::cout << ints.hasValue(0, 1, 2) << std::endl;
std::cout << ints.getValue(0, 1, 2) << std::endl;
ints.setValue(0, 1, 2, 47);
std::cout << ints.hasValue(0, 1, 2) << std::endl;
std::cout << ints.getValue(0, 1, 2) << std::endl;
return 0;
}
#包括
结构映射索引{
int x,y,z;
MapIndex()
:x(0),y(0),z(0){
}
MapIndex(整数x_,整数y_,整数z_)
:x(x_uu),y(y_u),z(z_u){
}
};
布尔运算符v2.z)
返回false;
如果(v1.zstd::cout
std::map
其中T
是您要保存的类型。您可以创建一个包含3个整数的结构,并将其用作映射的键。如果执行此操作,请记住设置运算符。如果您使用动态内存分配而不是静态数组,请查找“稀疏矩阵C++”在这方面,我更喜欢@memo1288的想法而不是@Code Guru的想法,因为它避免了在插入新元素时必须创建两个map
s的可能性,当然,除非您需要像“第一维中的第125行完全为空”这样的检查(v2.z、v2.y、v2.x)