Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Does `std::find()` short circuit?

Consider I had an std::vector such that its contents were std::strings and {"a","b","c"}. If I were to perform std::find() looking for "a", would it stop once it iterated over "a" (ie. short-circuit) or continue to the end?

std::vector<std::string> vec;
vec.insert(vec.begin(), "a");
vec.insert(vec.begin(), "b");
vec.insert(vec.begin(), "c");

Which is faster?

std::find(vec.begin(), vec.end(), "a");
std::find(vec.begin(), vec.end(), "c");
like image 537
gator Avatar asked Dec 03 '22 17:12

gator


2 Answers

See the possible implimenation of std::find

template<class InputIt, class T>
constexpr InputIt find(InputIt first, InputIt last, const T& value)
{
    for (; first != last; ++first) {
        if (*first == value) {  // if the condition met
            return first;       // ---> here returns the iterator
        }
    }
    return last;
}

It will stop iterating, once it finds the match.

like image 142
User Using Avatar answered Dec 17 '22 10:12

User Using


Based on description here, yes it does.

Returns the first element in the range [first, last) that satisfies specific criteria.

Complexity: At most last - first applications of the predicate

And by taking a look at its possible implementations it is stated that std::find uses short circuit

like image 24
MRB Avatar answered Dec 17 '22 12:12

MRB