Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Find the first value greater than user specified value from a map container

Tags:

c++

map

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!

like image 976
GoldenLee Avatar asked Jan 19 '23 19:01

GoldenLee


2 Answers

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.

like image 182
Mark B Avatar answered Feb 02 '23 00:02

Mark B


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));
like image 26
Kerrek SB Avatar answered Feb 01 '23 23:02

Kerrek SB