带字符串或结构键的std :: map

时间:2019-02-08 09:08:44

标签: c++ boost-serialization

我如何在c ++中映射struct或string类型的键值的std:map? 有可能这样做吗?现在,我正在使用具有键值int的映射进行内存映射,但是由于int的最大范围是有限的,并且程序中键值的最大大小为10 ^ 24左右,因此我被卡住了。所以通过将键类型用作struct或string可以解决此问题吗?

 int p0, p1, p2;
map<int,int> p0obj, p1obj, p2obj, size_p; int count = 0; 

                    float d0, d1, d2;                      
                    float a0 = a[p0];  
                    float b0 = b[p0]; 
                    float a1 = a[p1]; 
                    float b1 = b[p1];
                    float a2 = a[p2]; 
                    float b2 = b[p2];
                    if(d0>0 && d1>0 && d2>0) {
                        int key = d0+max_d*(d1+max_d*(d2+max_d*(a0+max_c*(b0+max_c*(a1+max_c*(b1+max_c*(a2+max_c*b2)))))));
        //std::string key = std::to_string(k);
                        p0obj[key] = p0; p1obj[key] = p1; p2obj[key] = p2; size_p[key]++;
                        oa << p0obj; oa << p1obj; oa << p2obj; oa << size_p;
                        std::cout<<"key="<<key<<std::endl;
                    }
                } 
            } 

1 个答案:

答案 0 :(得分:2)

似乎您想使用一堆float作为地图中的钥匙。

您可以通过将它们包装为tuple或定义更有意义的struct类型来做到这一点:

#include <map>

struct MyKey {
    float d0, d1, d2, a0, b0, a1, b1, a2, b2;

    bool operator < (const MyKey& o) const {
        return std::tie(d0, d1, d2, a0, b0, a1, b1, a2, b2) < std::tie(o.d0, o.d1, o.d2, o.a0, o.b0, o.a1, o.b1, o.a2, o.b2);
    }
};

struct MyValue {
    float p0, p1, p2;
};

std::map<MyKey, MyValue> pobj;

要插入此地图,请执行以下操作:

    pobj.insert({{d0, d1, d2, a0, b0, a1, b1, a2, b2}, {p0, p1, p2}});

但是不确定如何处理此类地图。用浮点数搜索可能效果不佳。但是用lower_bound可能仍然有用。

    auto it = pobj.lower_bound({d0, d1, d2, a0, b0, a1, b1, a2, b2});
    if (it != end(pobj)) {
        const MyKey& key = it->first;
        const MyValue& value = it->second;
        std::cout << "found: " << value.p0 << " " << value.p1 << " " << value.p2 << std::endl;
    }
相关问题