Q
Q
quad692021-12-29 06:02:02
C++ / C#
quad69, 2021-12-29 06:02:02

How can a union be used as the key of an unordered_map?

There is such a union:

union ObjectPos {
    unsigned short x;
    unsigned short y;
}


And I need to use it as a key for unordered_map: The problem is that there are N pieces of instances of the Object class and I need to find them by x and y. The specific number is unknown, and as the program runs, some objects are removed, and others may appear (everything happens in different coordinates). Of course, you can replace ObjectPos with a regular int and write a function that will make one int from two shorts (and vice versa), but this is extremely inconvenient...
std::unordered_map<ObjectPos , Object*> objects;


Answer the question

In order to leave comments, you need to log in

1 answer(s)
V
Vasily Demin, 2021-12-29
@quad69

You need to use a structure of two short values. For it, you will already need to define the hash function calculations, for example like this:

struct MyStruct {
    unsigned short x;
    unsigned short y;
};

template<>
struct std::hash<MyStruct> {
    std::size_t operator()(MyStruct const& s) const noexcept {
        return ((size_t)s.x << 16) | s.y;
    }
};

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question