简体   繁体   中英

A replacement for std::find_if and std::bind2nd on a sorted vector

I have a date class GregorianDate , and a std::vector<GregorianDate> instance dates . That vector is sorted.

Currently, given a GregorianDate instance date , I have the expression

std::vector<GregorianDate>::const_iterator it = std::find_if(
    dates.begin(),
    dates.end(),
    std::bind2nd(std::greater<GregorianDate>(), date)
);

I'm keen to replace this with

std::vector<GregorianDate>::const_iterator it = 
    std::lower_bound(dates.begin(), dates.end(), date);

since bind2nd is deprecated and dates is sorted.

Are the results of the two expressions identical for any date ?

The results are not the same. std::lower_bound gives you the first element in the set that is greater than or equal to the element you are looking for, or last if none are. std::find_if on the other hand will only return the element that the comparator returns true on and std::greater wont return true if the elements are equal.

You would need to use std::upper_bound to match your call to find_if ( upper_bound returns the first element greater than the element you are looking for), or change your comparator in find_if to match how lower_bound works.

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