I have a map container. How to return the first value greater than the user-specified search value by using find_if as follows:
std::map<string, int>::iterator it = find_if(Mymap.begin(), Mymap.end(), ......
Thank you very much!
Are you sure you want to be doing a linear search for any item with a value greater than your criteria through the container?
It would probably be better to also keep a separate index of sorted values that you could call upper_bound
on, performing in logarithmic time rather than linear in the number of elements. Alternately look into boost::multi_index
instead.
With a lambda:
int n = MYVALUE;
auto it = std:: find_if(Mymap.begin(), Mymap.end(),
[n](const std::pair<std::string, int> & x) -> bool
{ return x.second > n; }
);
(If the value is fixed you can put it directly inside the lambda body. For C++14 and later, the lambda capture can be [n = MYVALUE]
and you don't need a separate outer variable n
.)
With a predicate:
struct Finder
{
Finder(int n_) : n(n_) { }
int n;
bool operator()(const std::pair<std::string, int> & x) const
{
return x.second > n;
}
};
auto it = std::find_if(Mymap.begin(), Mymap.end(), Finder(MYVALUE));
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With