It’s a very useful function to find elements in map.

iterator lower_bound (const key_type& k);
Returns an iterator pointing to the first element in the container whose key is not considered to go before k (i.e., either it is equivalent or goes after).

iterator upper_bound (const key_type& k);
Returns an iterator pointing to the first element in the container whose key is considered to go after k.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
#include <stdio.h>
#include <stdlib.h>
#include <map>
#include <iostream>
using namespace std;

int main(){
std::map<char,int> mymap;
std::map<char,int>::iterator itlow,itup;

mymap['a']=0;
mymap['b']=0;
mymap['d']=0;
mymap['t']=0;
mymap['x']=0;

itlow=mymap.lower_bound ('c');
// find the first key element that is at least greater(>=) than 'c'
// in this case, it's 'd'

itlow=mymap.lower_bound ('b');
// find the first key element that is at least greater(>=) than 'c'
// in this case, it's 'd'

itup=mymap.upper_bound ('d');
// find the first element that is definite greater than 'd'
// point to something > 'd' and not including 'd', so it's 't'

cout << itlow->first << " " << itlow->second<<endl;
cout << itup->first << " " << itup->second<<endl;
}

reference:
https://goo.gl/BkfLdA
https://goo.gl/TXon4t