Find the first value that exceeds the value specified by the user from the map container

I have a card container. How to return the first value that exceeds the user-specified search value using find_if as follows:

std::map<string, int>::iterator it = find_if(Mymap.begin(), Mymap.end(), ...... 

Many thanks!

+4
source share
4 answers

Using 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 in the lambda body.)

With the predicate:

 struct Finder { Finder(int n_) : n(n_) { } int n; bool operator()(const std::pair<std::string, int> & x) const { return x.second > n; } }; std::find_if(Mymap.begin(), Mymap.end(), Finder(MYVALUE)); 
+3
source

Are you sure you want to perform a linear search for any element with a value greater than your criteria through the container?

It would probably be better to keep a separate index of the sorted values, which could be called upper_bound on, performing in logarithmic time, rather than linearly in the number of elements. boost::multi_index .

+4
source

For C ++ 03, you need to provide a comparator object or handle some complex bindings:

 typedef map<string, int>::value_type Value; struct Comp { Comp(int v) : m_v(v) { } bool operator()(const Value& v) const { return v.second > m_v; } int m_v; }; void f() { map<string, int> Mymap; map<string, int>::iterator it = find_if(Mymap.begin(), Mymap.end(), Comp(42)); } 
+2
source

You can find B. Stroustup's book very useful when it comes to STL functions. And he offers this code:

 bool gt_42 (const pair <const string ,int>& r ) { return r.second >42 ; } void f (map <string,int >& m ) { typedef map <string ,int >:: const_iterator MI ; MI i = find_if (m.begin (), m.end (), gt_42 ); // ... } 

From the chapter "Overview of the standard library" (available in the .pdf file) "C ++ programming language, special version"

0
source

Source: https://habr.com/ru/post/896811/


All Articles