On 27.01.2017 16:17, Christopher J. Pisz wrote:
>
[snip]
> How complex is std::find(substr, offset)?
> I wonder if I am barking up the wrong tree.
It's clear that your task is finding a substring, possibly just a string
prefix, and `std::find` does not support either of those tasks. The
title of the post also indicates that you meant to refer to
`std::basic_string::find` here. I.e., `s.find( substr, offset )` with
`s` a `std::basic_string<T>` for some suitable character type `T`.
`std::basic_string::find` has four overloads, two of which match the
informal argument specification above.
The complexity is not specified by the standard, but with simplest
possible straightforward implementation a call `s.find( t )` has complexity
O(SL*length(t))
where SL = max( length(s) - length(t), 0).
This is then the worst case.
For the best case a quality implementation should tend to complexity
O(SL), by never examining a character in s more than once. Wikipedia on
the Knuth-Morris-Pratt: “the expected complexity of searching string S[]
of length k is on the order of k comparisons or O(k)”. However, the
expected complexity, what you'll usually get, is not the worst case,
whcih is as noted above. I don't know how likely the worst case is.
As I recall it I first became familiar with the KMP algorithm via an
article in Scientific American by Niklaus Wirth (!), about how one could
apply simple transformations to algorithms. But I may possibly have a
false memory there, because I've never been able to find that article
again. On the other hand I've not searched for it lately.
Cheers & hth.!,
- Alf