c++ - 如何用 map 表示 3D 数组?

标签 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_, 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;
}

关于c++ - 如何用 map 表示 3D 数组?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19062874/

相关文章:

c++ - CDHtmlDialog 没有加载最新版本的 IE?

c++ - 生态二维结构数组 C++

c++ - 使用类构造函数在线程中启动成员函数

c++ - 是否可以将可变参数宏字符串化为逗号分隔的字符串列表?

c++ - 如何在 C++ 中获得大数的第 n 个根?

c++ - 在 CLion 上链接 Qt

c++ - 相互依赖任务的线程池

c++ - 如何使用 boost lexical_cast 将字符串转换为 unsigned short?

c++ - 是否可以禁用编译器警告 C4503?

c++ - 检测对临时的悬空引用