5 ms·
Although I agree that it would seem natural to have such a method in a standard container class, I would like to make a couple of observations. First, there ar
by Koshkin 10y ago
Although I agree that it would seem natural to have such a method in a standard container class, I would like to make a couple of observations.
First, there are containers that do have a find() method, std::map, for example (although not on a condition). It could be a wrong impression, but to me this tells something. Perhaps, if I intend to do a search, I might be better off using a different structure (rather than a list) that is more suitable for searching, or maybe a different - more efficient - algorithm (such as binary_search(), if applicable).
Second, if you use a container as a part of your own class, defining a find() method is trivial.
I have no doubt that there are other, more technical reasons for the standard library being the way it is, for example, the idea of separation of algorithms from containers by means of iterators.
- clishem 10y agoThe reason is that `std::find` is O(N) while `std::map::find` is O(1).
- slavik81 10y agoIt doesn't affect your point, but std::map::find is O(log n). std::map is ordered and is typically a tree.
- WildUtah 10y agoYes, except the canonical map is—surprising the users of other collection frameworks—an ordered, balanced tree. So std::map::find() is O(ln n) while std::unordered_map::find() is O(1).
- mschuetz 10y agoFind probably wasn't the best example but even with find, I sometimes want to look for an item in a vector with 20 elements. In cases like that, I'm fine if find() has to apply a comperator to every element until it finds the first that matches. And functions like map (apply function to each element of a collection), filter (return new collection with all elements that match a condition) and possibly some others have to be applied to all elements in a collection anyway. > Second, if you use a container as a part of your own class, defining a find() method is trivial. It is, but I'd rather not have to define 20 trivial things when I start a new project.