Reputation: 4275
I have an unordered map of Foo objects and I would like to efficiently test, if the key set contains of Foo objects with a given id.
One way would be to construct a Foo object and set it's id to the query value, but I am wondering if there is a more elegant way to achieve this (maybe with a different data structure)?
class Foo {
public:
int id;
};
namespace std
{
template<>
struct hash<Foo> {
std::size_t operator()(Foo const& f) const {
return std::hash<int>()(f.id);
}
};
template<>
struct equal_to<Foo> {
bool operator()(const Foo &lhs, const Foo &rhs) const {
return lhs.id == rhs.id;
}
};
}
int main() {
unordered_map<Foo, int> dict;
Foo f;
f.id = 123;
dict[f] = 1;
//How to test if Foo object with id x is present in dict?
}
Upvotes: 0
Views: 123
Reputation: 138041
No, there is no more efficient way than creating a Foo
object with the id
that you want to test with this current collection. You are "stuck" using the key type that you chose in the first place.
If you want to index the dictionary by an int
property, consider making that property the key and having the Foo
object part of the value. (That could look like unordered_map<int, pair<Foo, int>>
in this case.)
Upvotes: 3