tags:

views:

317

answers:

5

I have a std::map that I'm using to store values for x & y coordinates. Currently I'm creating a std::string with the two coordinates (ie "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.

+19  A: 

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;
David Norman
+1  A: 

Boost has a map container that uses one or more indices.

Multi Index Map

DeadHead
+4  A: 

I usually solve this kind of problem like this:

struct Point
{
public:
    Point() : x(0), y(0) {}
    Point(int inX, int inY) : x(inX), y(inY) {}
    int x, y;
};

bool operator <(const Point & lhs, const Point & rhs) // lhs = left-hand side
                                                      // rhs = right-hand side
{
    if (lhs.x != rhs.x)
    {
     return lhs.x < rhs.x;
    }
    else
    {
     return lhs.y < rhs.y;
    }
}
int main()
{
    Point p1(0, 1);
    Point p2(0, 2);
    std::map<Point, std::string> mapping;
    mapping[p1] = "p1";
    mapping.insert(std::make_pair(p2, "p2"));
    return 0;
}
StackedCrooked
This is explicit, which is good. Just note this is the same as `typedef std::pair<int, int> Point;`
GMan
Heh, until now I didn't know that std::pair has operator< defined. Love SO!
StackedCrooked
+1  A: 

What are the requirements on a class that is to be used as the key?

The map needs to be able to tell whether one key's value is less than another key's value: by default this means that (key1 < key2) must be a valid boolean expression, i.e. that the key type should implement the 'less than' operator.

The map template also implements an overloaded constructor which lets you pass-in a reference to a function object of type key_compare, which can implement the comparison operator: so that alternatively the comparison can be implemented as a method of this external function object, instead of needing to be baked in to whatever type your key is of.

ChrisW
A: 

Use std::pair. Better even use QHash,int> if you have many of such mappings.

MadH