Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the best way to use two keys with a std::map?

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.

like image 447
Roland Rabien Avatar asked Jul 11 '09 00:07

Roland Rabien


People also ask

Can a map have 2 Keys C++?

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.

Can a map have 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.

Can keys be pairs in maps?

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!

Can a Key have multiple values C++ map?

Some keys can have multiple values. For example, "the" => "dog" || "wall" || "cat" || "house". The value is randomly chosen from those for that key.


2 Answers

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; 
like image 103
David Norman Avatar answered Oct 09 '22 07:10

David Norman


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;     } } 
like image 26
StackedCrooked Avatar answered Oct 09 '22 07:10

StackedCrooked