If I wouldn't have checked and looked, I would have suspected that the built-in member s1.find() should return an iterator and not a size_t (unsigned integral). |
std::find just steps through each element, one by one, until it finds the value or reaches the end. Most containers doesn't have a find member function and you're just supposed to use std::find.
std::set/std::map (and the equivalent unordered containers) do have a find member function (
that returns an iterator) because these containers provide a more efficient way to look up the elements. Using std::find would be suboptimal for these containers.
std::string is a bit special. It does indeed have a find member function that returns an index. It feels like it tries to be user-friendly by providing a lot of member functions while at the same time providing an interface that is consistent with the other containers. Part of the reason might be that the initial design was made before the standard algorithms and the other containers where added.
I have an early draft of the C++ standard from 1994 (N0414). It contains a string class that is very similar to std::string. It does not contain the other containers that we know today (vector, deque, list, etc.) and it also doesn't contain any of the standard algorithms (I don't think it even mention iterators). It does however contain a container called
dynarray (similar to std::vector) but that one also used indices instead of iterators.
It is also safer to dereference an iterator, since it checks that one does not go beyond the container boundaries during compile time and less safer to use the subscript [] that is without the boundary check. |
None of them are bounds-checked at compile time. Both of them can be checked at runtime in a debug build.
I would have assumed they should have also overloaded the algorithm find() with the ability to find strings, with the iterator return being the first char of the search. |
That's what std::search is for.
https://en.cppreference.com/w/cpp/algorithm/search
I also noticed that the algorithm find() does not take a string, but a single character only. So I gather that they intended the algorithm find() to be used for single characters only and if you want to find strings, then use the string member find() with size_t return. |
std::find is meant to be useful, and work the same way, for any container (it doesn't even have to be a container as long as you can iterate over it using iterators).