Should I return an iterator or an index from a string search algorithm?
In particular, I'd like to conform to C++'s convention. Templated functions such as std::find
returns an iterator because it has to since some containers are not indexible. More specialized functions such as std::string::find
returns a size_t
index.
The check for failure is == x.end()
for std::find
and == std::string::npos
(usually -1) for the specialized version. I think the iterator checking method is more elegant.
Internally, I'll be using indices for performance and convenience reasons regardless of return type.
What are the advantages and disadvantages to each style of returning when I fix the input types (std::string
)?
If you want to be STL-compliant (although even STL is not perfectly designed and
std::string
is the canonical example where indexes and iterators are mixed up), you should use an iterator. Then, can usestd::distance
to find the position in terms oftypename iterator_traits<InputIterator>::difference_type
(i.e., most of the time astd::size_t
). Of course, this will have an overhead ofO(n)
for non-random access iterators, but it is the most compliant approach.Hopefully in the future ranges will make it into the standard library http://www.boost.org/doc/libs/1_57_0/libs/range/doc/html/index.html