2

I want to create a map that uses my custom class as the key and element. However, I am getting errors when inserting. I have found a post related to my question here, C++ STL - Inserting a custom class as a mapped value. But the solution proposed did not help me.

/*
 * Structure for a coordinate
 * This is the custom class that I created 
 */
class Coord{ 
    public:
        int x, y;

    public:
        Coord(int x1, int y1) {
            x = x1;
            y = y1;
        }
        int getX(void) {
            return x;
        }
        int getY(void) {
            return y;
        }
};

/*
 * I attempted to create a map<Coord, Coord>
 * and attempted to insert Coord values in. I get
 * compile time error
 */
map<Coord, Coord> came_from; 
came_from.insert(Coord(0,0), Coord(5,5));

I get this error.

invalid operands to binary expression ('Coord' and 'Coord')
for (const_iterator __e = cend(); __f != __l; ++__f)
                                              ~~~ ^  ~~~

What does this mean?

Edit 1

Actually order doesn't matter for me, so I think unordered_map is more appropriate in this case.

I changed to unordered_map and used emplace as suggested in comment. New Code below:

unordered_map<Coord, Coord> came_from; 
came_from.emplace(Coord(0,0), Coord(0,0));

I get a an error indicating the hash function is not meeting requirements. Below are the exact error messages.

static_assert failed due to requirement '__check_hash_requirements<__hash_value_type<Coord, Coord>,
      int>::value' "the specified hash does not meet the Hash requirements"
    static_assert(__check_hash_requirements<_Key, _Hash>::value,

I guess I need to define a custom hash function right? How do I do that?

cruise_lab
  • 649
  • 8
  • 21

0 Answers0