You need to create a constructor for your class that takes int
as its only argument. Doing so allows implicit conversion from int
to your class, making it possible to call std::set::find(int)
, as requested.
For example:
#include <iostream>
#include <set>
class Foo {
public:
/* Normal constructor */
Foo(const char * s, int i) : str(s),id(i) {}
/* Special constructor for implicit conversion */
Foo(int i) : str(0),id(i) {}
/* Make Foo usable with std::set */
bool operator<(const Foo& f) const { return f.id<id; }
/* Make Foo printable */
friend std::ostream& operator<<(std::ostream& o, const Foo& f);
private:
const char * str;
int id;
};
std::ostream& operator<<(std::ostream& o, const Foo& f) {
return o << "(" << f.str << " " << f.id << ")";
}
typedef std::set<Foo> FooSet;
int main(void) {
FooSet s;
s.insert(Foo("test",1));
s.insert(Foo("asdf",7));
s.insert(Foo("spam",3));
for (int i=0; i<10; ++i) {
/* Note that searching is done via FooSet::find(int id) */
FooSet::const_iterator f = s.find(i);
std::cout << "Searching for id " << i << ": ";
if (f==s.end())
std::cout << "absent";
else
std::cout << "present " << *f;
std::cout << std::endl;
}
return 0;
}
This yields:
Searching for id 0: absent
Searching for id 1: present (test 1)
Searching for id 2: absent
Searching for id 3: present (spam 3)
Searching for id 4: absent
Searching for id 5: absent
Searching for id 6: absent
Searching for id 7: present (asdf 7)
Searching for id 8: absent
Searching for id 9: absent