stl::map
私はキータイプがカスタム構造体です。私は、このマップが、他のコンポーネントの値に関係なく、コンポーネントとして特定の文字列(以下「id」と表記)を持つキーをすでに持っているかどうかを知りたいです。 this答えとthis 1も、私はカスタムfunctor
でstl::find_if
を使用しように触発さ:C++では、キーが文字列で構成されている場合、ファンクタ付きのマップ上でfind_ifを使用する方法は?
map<myStruct, vector<size_t> > myMap;
struct myStruct
{
string a, b, c, id;
};
struct checkId : unary_function<pair<myStruct, vector<size_t> >, bool>
{
private:
string _exp;
public:
checkId (myStruct x) : _exp(x.id) {}
bool operator() (const pair<myStruct, vector<size_t> > & p) const
{
return p.first.id.compare(_exp) == 0;
}
};
map<myStruct, vector<size_t> >::iterator it;
myStruct newS; // to be initialized, but not shown here
it_mP2P = find_if(myMap.begin(), myMap.end(), checkId(newS));
私はこれをコンパイルすると、gccが私を返します。
/usr/lib/gcc/x86_64-redhat-linux/4.1.2/../../../../include/c++/4.1.2/bits/stl_function.h: In member function ‘bool std::less<_Tp>::operator()(const _Tp&, const _Tp&) const [with _Tp = myStruct]’:
/usr/lib/gcc/x86_64-redhat-linux/4.1.2/../../../../include/c++/4.1.2/bits/stl_map.h:347: instantiated from ‘_Tp& std::map<_Key,_Tp, _Compare, _Alloc>::operator[](const _Key&) [with _Key = myStruct, _Tp = std::vector<long unsigned int, std::allocator<long unsigned int> >, _Compare = std::less<myStruct>, _Alloc = std::allocator<std::pair<const myStruct, std::vector<long unsigned int, std::allocator<long unsigned int> > > >]’
myprogram.cpp:386: instantiated from here
/usr/lib/gcc/x86_64-redhat-linux/4.1.2/../../../../include/c++/4.1.2/bits/stl_function.h:227: error: no match for ‘operator<’ in ‘__x < __y’
これは私がオーバーロードしなければならないことを意味しています"<"演算子は、自分のファンクタ "checkId"を使用したい場合、私のカスタム構造体で動作しますか?これどうやってするの?私はC++のエキスパートではありませんので、事前にコードをお読みいただきありがとうございます。
キーとして体mystructを使用してマップを作成するために '演算子<'(またはカスタム述語)を必要とするように見えます。 find_ifとは関係ありません。 – UncleBens
ヒント:http://codepad.org/n7yWIRnQあなたのファンクタとは関係ありません –