问题
With template functions from <algorithm>
you can do things like this
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 have to 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}; // don't need a full foo object;
auto it = foos.find(search_dummy);
It would be so helpful if one can call just foos.find(2)
. Is there any reason why find
can't be a template, accepting everything that can be passed to the less predicate. And if it is just missing, why isn't it in C++11 (I think it isn't).
Edit
The main question is WHY isn't it possible and if it was posiible, WHY decided the standard not to provide it. A a second question you can propose workarounds :-) (boost::multi_index_container
crosses my mind just now, which provides key extraction from value types)
Another Example with a more expensive to construct value type. The key name
is part of the type and should not be used as a copy in maps key;
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;
};
回答1:
std::find_if
works on an unsorted range. So you can pass any predicate you want.
std::set<T>
always uses the Comparator
template argument (std::less<T>
by default) to maintain the order of the collection, as well as find elements again.
So if std::set::find
was templated, it would have to require that you only pass a predicate that observes the comparator's total ordering.
Then again, std::lower_bound
and all the other algorithms that work on sorted ranges already require exactly that, so that would not be a new or surprising requirement.
So, I guess it's just an oversight that there's no find_if()
(say) on std::set
. Propose it for C++17 :) (EDIT:: EASTL already has this, and they used a far better name than I did: find_as
).
That said, you know that you shouldn't use std::set, do you? A sorted vector will be faster in most cases and allows you the flexibility you find lacking in std::set
.
EDIT: As Nicol pointed out, there're implementations of this concept in Boost and Loki (as well as elsewhere, I'm sure), but seeing as you can't use their main advantage (the built-in find()
method), you would not lose much by using a naked std::vector
.
回答2:
The standard states that std::set::find
has logarithmic time complexity. In practice this is accomplished by implementing std::set
as a binary search tree, with a strict weak ordering comparison used as sorting criteria. Any look-up that didn't satisfy the same strict weak ordering criteria wouldn't satisfy logarithmic complexity. So it is a design decision: if you want logarithmic complexity, use std::set::find
. If you can trade complexity for flexibility, use std::find_if on the set.
回答3:
They've provided for what you want, but in a rather different way than you're considering.
Actually, there are two different ways: one is to build a constructor for the contained class that 1) can be used implicitly, and 2) requires only the subset of elements that you really need for comparison. With this in place, you can do a search for foods.find(2);
. You will end up creating a temporary object from 2
, then finding that temporary object, but it will be a true temporary. Your code won't have to deal with it explicitly (anywhere).
Edit: What I'm talking about here would be creating an instance of the same type as you're storing in the map, but (possibly) leaving any field you're not using as a "key" un-initialized (or initialized to something saying "not present"). For example:
struct X {
int a; // will be treated as the key
std:::string data;
std::vector<int> more_data;
public:
X(int a) : a(a) {} // the "key-only" ctor
X(int a, std::string const &d, std::vector<int> const &m); // the normal ctor
};
std::set<X> s;
if (s.find(2)) { // will use X::X(int) to construct an `X`
// we've found what we were looking for
}
Yes, when you construct your X
(or what I've called X, anyway) with the single-argument constructor, chances are that what you construct won't be usable for anything except searching.
end edit]
The second, for which the library provides more direct support is often a bit simpler: if you're really only using some subset of elements (perhaps only one) for searching, then you can create a std::map
instead of std::set
. With std::map
, searching for an instance of whatever you've specified as the key type is supported explicitly/directly.
回答4:
key_type is a member type defined in set containers as an alias of Key, which is the first template parameter and the type of the elements stored in the container.
See documentation.
For user-defined types there is no way for the library to know what the key type is. It so happens that for your particular use case the key type is int
. If you use a set< int > s;
you can call s.find( 2 );
. However, you will need to help the compiler out if you want to search a set< foo >
and want to pass in only an integer (think how will the set
's ordering work between foo
and an int
).
回答5:
Because if you want to do std::find(2)
you'll have to define how int
will compare with foo
in addition to the comparison between two foo
s. But since int
and foo
are different types, you will need actually two additional functions:
bool operator<(int, foo);
bool operator<(foo, int);
(or some other logical equivalent pair).
Now, if you do that, you are actually defining a bijective function between int
and foo
and you could as well simply use a std::map<int, foo>
and be done.
If you still don't want the std::map
but you want the benefits of a sorted search, then the dummy object is actually the easiest way to go.
Granted, the standard std::set
could provide a member function, to which you pass a function that receives a foo
and return -1, 0, 1 if it is less, equal or greater than the searched one... but that's not the C++ way. And note that even bsearch()
takes two arguments of the same type!
来源:https://stackoverflow.com/questions/11066859/why-is-setfind-not-a-template