Why does std::set provide a .find() method that takes a reference to an item to be found? |
std::set::find(const Key& key)
takes a
const reference to the
Key object to be searched, because there is
no point in passing the
Key object
by-value. Passing the
Key object
by-value (rather than
by-reference) would effectively create and pass a
copy of that object into the function – which is an unnecessary overhead here!
Or, in other words: In order to search a key in the set, it is perfectly sufficient to have a
const reference to the
Key object that is to be found. Why would you need a "full" local copy of that object?
For "simple" types, like
int or
long, it probably doesn't make much of a difference, in terms of performance, whether we pass a
reference or a
copy. But for "large" classes (objects) it can make a significant difference!
_____
If you have the item you want to look for, what's the point of searching for it in a container? |
For example, because you want to know whether the set contains a given item? Suppose that you have a "whitelist" which is stored as a
std::set<std::string>
. Now, when you get
some std::string
as input, you have to check whether that given string is in the "whitelist" or not.
std::set::find()
does exactly that.
Note:
std::set::find()
does
not find "the"
Key object that you pass. It finds
any Key object in the set that compares "equal" to the given
Key object! So, for example, if we are searching for an
std::string
, then we will find
any std::string
object in the set whose text is "equal" to the given
std::string
object's text.
💡 Precisely, two objects (keys) are considered "equivalent", if neither object compares
less than the other.