Using template functions from <algorithm>
you can do such things
struct foo { int bar, baz; }; struct bar_less { // compare foo with foo bool operator()(const foo& lh, const foo& rh) const { return lh.bar < rh.bar; } template<typename T> // compare some T with foo bool operator()(T lh, const foo& rh) const { return lh < rh.bar; } template<typename T> // compare foo with some T bool operator()(const foo& lh, T rh) const { return lh.bar < rh; } }; int main() { foo foos[] = { {1, 2}, {2, 3}, {4, 5} }; bar_less cmp; int bar_value = 2; // find element {2, 3} using an int auto it = std::lower_bound(begin(foos), end(foos), bar_value, cmp); std::cout << it->baz; }
In std::set
methods like find
, you must pass an object of type set::key_type
, which often forces you to create a dummy object.
set<foo> foos; foo search_dummy = {2,3};
It would be helpful if you could just foos.find(2)
. Is there a reason why find
cannot be a pattern, accepting anything that can be passed to a less predicate. And if it's just missing, why not in C ++ 11 (I think it's not).
Edit
The main question: WHY it is impossible, and if it were possible, WHY decided that the standard should not provide it. The second question you can suggest workarounds :-) ( boost::multi_index_container
now sorting through my mind, which provides key extraction from value types)
Another example with more expensive value type construction. The name
key is part of this type and should not be used as a copy in the map file;
struct Person { std::string name; std::string adress; std::string phone, email, fax, stackoferflowNickname; int age; std::vector<Person*> friends; std::vector<Relation> relations; }; struct PersonOrder {