0
Fooオブジェクトの順序付けられていないマップがあります。キーセットに指定されたIDを持つFooオブジェクトが含まれている場合、効率的にテストしたいと思います。std :: unordered_map <Foo, Bar>特定のFooキーが存在するかどうかテストする
Fooオブジェクトを作成し、そのIDをクエリ値に設定するのが1つの方法ですが、これを達成するためのもっとエレガントな方法があるかどうかは疑問です。
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?
}
あなたの質問には「x」とは何ですか? –
@ Kerrek SB It's 42 – user695652
C++ 14では、 'std :: map>'を使い、異種の検索を行います。一時的な 'Foo'。また、 'equal_to'を特化しないでください。 '演算子=='を書くか、独自の述語型を定義してください。 –