简体   繁体   中英

Is find_if on a set linear?

I've ran into a case where set::find is not the correct way to find the object because I'm finding the object in a different way (by std::find_if) than it is ordered in the set. I have not found any complexity information on finding elements this way. I assume it's linear because iterating through a "unordered" container to find a match is linear.

Yes, linear it is.

From this ref :

Complexity

Up to linear in the distance between first and last: Calls pred for each element until a match is found.

where the prototype is:

template<class InputIterator, class UnaryPredicate>
   InputIterator find_if (InputIterator first, InputIterator last, UnaryPredicate pred)

And from another ref :

Complexity

At most last - first applications of the predicate

You can look here and see that the complexity of find_if is linear.

It is because find_if is a generalized algorithm and it doesn't know a certain type of container it works with. So it can't use peculiarities of different containers to boost a search process and just checks all the elements to find the appropriate one.

Yes, it is linear in complexity.

The iterator argument is an InputIterator, which is unidirectional. The only conceivable implementation is to iterate forward over each element and check the predicate. Because the predicate is arbitrary, it is not possible to specialise the algorithm for different container types in order to improve algorithmic complexity.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM