Possible Duplicate:
C++ string::find complexity
What is the time complexity of the find operation that comes built-in with the string library in STL?
Possible Duplicate:
C++ string::find complexity
What is the time complexity of the find operation that comes built-in with the string library in STL?
The Standard, §21.4.7.2, doesn't give any guarantees as to the complexity.
You can reasonably assume std::basic_string::find
takes linear time in the length of the string being searched in, though, as even the naïve algorithm (check each substring for equality) has that complexity, and it's unlikely that the std::string
constructor will build a fancy index structure to enable anything faster than that.
The complexity in terms of the pattern being searched for may reasonably vary between linear and constant, depending on the implementation.
As pointed out in comments, standard doesn't specify that.
However, since std::string
is a generalized container and it can't make any assumptions about the nature of the string it holds, you can reasonably assume that complexity will be O(n)
in case when you search for a single char
.
At most, performs as many comparisons as the number of elements in the range [first,last).