I have a std::map
that I'm using to store values for x and y coordinates. My data is very sparse, so I don't want to use arrays or vectors, which would result in a massive waste of memory. My data ranges from -250000 to 250000, but I'll only have a few thousand points at the most.
Currently I'm creating a std::string
with the two coordinates (i.e. "12x45"
) and using it as a key. This doesn't seem like the best way to do it.
My other thoughts were to use an int64 and shove the two int32s into it and use it as a key.
Or to use a class with the two coordinates. What are the requirements on a class that is to be used as the key?
What is the best way to do this? I'd rather not use a map of maps.
Implement a MultiKeyMap in C++A MultiKeyMap is a map that offers support for multiple keys. It is exactly the same as a normal map, except that it needs a container to store multiple keys.
Class MultiKeyMap<K,V> A Map implementation that uses multiple keys to map the value. This class is the most efficient way to uses multiple keys to map to a value. The best way to use this class is via the additional map-style methods.
Do you mean cout << mymap[make_pair(1,2)] << endl; ? (1,2) is non-sensical, at least in this context. You must have an std::pair to be used as your key, and that means following what @andre just commented. Yes!
Some keys can have multiple values. For example, "the" => "dog" || "wall" || "cat" || "house". The value is randomly chosen from those for that key.
Use std::pair<int32,int32> for the key:
std::map<std::pair<int,int>, int> myMap; myMap[std::make_pair(10,20)] = 25; std::cout << myMap[std::make_pair(10,20)] << std::endl;
I usually solve this kind of problem like this:
struct Point { int x; int y; }; inline bool operator<(const Point& p1, const Point& p2) { if (p1.x != p2.x) { return p1.x < p2.x; } else { return p1.y < p2.y; } }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With