Hi
I have a vector containing an list of integers I need to search for. I'm
not sure how the find() algorithm works internally so if I sort the vector
will it speed up find() or should I not bother? Does the same apply to a
list?
Exact definition of std::find() is left to the implementation. The
standard guanratees that this algorithm runs in worst case O(n), where
n is the length of the segment we wish to run the search on. However,
it does not guarantee any kind of "performance improvements" if the
container is sorted. Moreover,
(a) There is no way you can tell std::find that the vector is sorted.
(b) A vector is a "sequence" container, which means that the order of
the elements in it matters. You would end up in changing the order
while sorting, even if you don't intend that.
Finally, even if we assume that you use a sorting algorithm and then a
hypothetical "optimized" find() on the sorted container, you would end
up with complexity O(n log(n)) + O(log(n)), i.e. O(n log(n)), which is
not as better as O(n) guaranteed by std::find.
std::list is also a sequence container, and hence the same would apply
for std::list too.
Thanks.