模板函数来自<algorithm>
你可以做这样的事情
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
方法如find
你必须传递一个类型的对象set::key_type
这通常会迫使您创建一个虚拟对象。
set<foo> foos;
foo search_dummy = {2,3}; // don't need a full foo object;
auto it = foos.find(search_dummy);
如果有人可以打电话的话,那就太有帮助了foos.find(2)
。有什么理由吗find
不能是模板,接受可以传递给 less 谓词的所有内容。如果它只是丢失了,为什么 C++11 中没有它(我认为不是)。
Edit
主要问题是为什么它不可能,如果它是可能的,为什么决定标准不提供它。第二个问题您可以提出解决方法:-) (boost::multi_index_container
我刚才想到的是,它提供了从值类型中提取键的功能)
构造值类型更昂贵的另一个示例。钥匙name
是类型的一部分,不应用作映射键中的副本;
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
{
// assume that the full name is an unique identifier
bool operator()(const Person& lh, const Person& rh) const
{
return lh.name < rh.name;
}
};
class PersonRepository
{
public:
const Person& FindPerson(const std::string& name) const
{
Person searchDummy; // ouch
searchDummy.name = name;
return FindPerson(searchDummy);
}
const Person& FindPerson(const Person& person) const;
private:
std::set<Person, PersonOrder> persons_;
// what i want to avoid
// std::map<std::string, Person> persons_;
// Person searchDummyForReuseButNotThreadSafe;
};