Martin Martin - 1 year ago 98
C++ Question

No find member in std::vector

Is there any particular reason why

does not have a member function
? Instead you have to call
#include <algorithm>

The reason why I ask is that I think it would be a good thing to be able to change container class in some piece of implementation without having to change the code wherever the container is accessed. Say I replace an
where the implementation uses
with an
. Then I also have to replace the call of
with a call to the member
, unless I want to keep the linear complexity of
. Why not just have a member
for all container classes, which finds an element with whatever algorithm is best suited for each container?

Answer Source

Conceptually, std::find only requires two InputIterators to work and not an std::vector. As such, one implementation works for all containers including STL containers, and standard arrays, and anything that can supply an InputIterator, including for example an istream_iterator() - nice!

So, instead of providing one find() method for every container (and take into account that for some it might not possible, like standard arrays), one single, generic find() function is provided for all. This likely makes your code more resilient to change than adding a find() method for each container since it provides a consistent interface to search in any collection: an input stream from console, network etc., or just a basic array. This is an important aspect of the STL generic design philosophy: you can search for elements in any collection/range defined by two InputIterators.

The downside, as you note, is that in some cases, better performance may be achieved using the container's own method, which can make special assumptions to improve performance (similarly for list::remove, unorderd_map::remove/find() etc.). For this reason, containers can provide (and this is a well known design feature of STL) a method specifically for performance reasons: for example a std::unordered_map does not require one to iterate through the entire map to find an element.

In summary, since the generic std::find works efficiently for a vector, there is no need to provide a member function, since it might enforce even less portable design.

For all things STL related see The C++ Standard Library - A Tutorial and Reference, 2nd Edition