Search code examples
c++algorithmperformancestltradeoff

Is std::find suitable only for containers whose elements may be not sorted?


We can use std::find on std::set, but it may be slow because std::set has a member function std::set::find that is often faster than std::find.

Is std::find suitable only for containers whose elements may be not sorted, e.g. std::list?

Can std::find prevent the user from using it to find something on std::set?


Solution

  • Generally speaking you can use std::find with all the containers which provide you with input iterators. Here is the info about std::find with its iterator requirements.

    The main question is effectiveness. The algorithm does not know anything about the inner representation of the container it works with. So std::find simply iterates over the elements of the particular container.There is no way to prevent it from dealing with containers like std::set. Moreover, it will be contradictory to the design of STL.

    As a general rule you should prefer container methods to the algorithms with the same name.