Reputation: 7841
How can I represent a 3D array like
myarray[1000][1000][1000];
this is a large array which gives memory limit exceeded. Every cell will not be used so there is a huge waste of memory. I want to map 3 numbers and the value, Is there any other way to do this?
Upvotes: 1
Views: 1257
Reputation: 26409
#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;
}
Upvotes: 3