Dinesh Lama
Dinesh Lama

Reputation: 141

std::map with string or struct key

How do i memory map a std:map of key value of type struct or string in c++? Is this possible to do so? Right now i'm doing memory mapping with a map with key value int, but since max range of int is limited and the max size of the key value in my program is around 10^24, i'm stuck. so by either using key type as struct or string can i solve this problem?

 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;
                    }
                } 
            } 

Upvotes: 2

Views: 976

Answers (1)

rustyx
rustyx

Reputation: 85371

It seems you want to use a bunch of floats as the key in a map.

You can do it either by wrapping them as a tuple or define a more meaningful struct type:

#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;

To insert into this map:

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

Not sure however what you would do with such a map. Searching by floats will probably not work out well. But looking up a subspace with e.g. lower_bound might still be useful.

    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;
    }

Upvotes: 2

Related Questions