map::lower_bound function

The map::lower_bound function purpose is to find the first position of the element before which the key will be inserted.

iterator lower_bound(const key_type& x);

key_type:type of the key ;

LinK:key_type of pair.

x – The key of the pair element you want to insert into the container.

Return type
iterator -It points to the element with larger or equal key value.If the key supplied is larger than the largest key of the elements in the container the end() is return.

If you are confuse with what this function does then just remember one thing,for any value passed as argument(x) the return iterator will point to element with key>=x.

Link:map::end function

Code example

map<int,string>mp{{ 5 ,”Five” } , { 3 ,”three” } , { 89 , “Eighty-nine” }};

map<int,string>::iterator it=mp.lower_bound(4);

cout<< it->first << ” ” << it->second << endl ;

mp.insert( {4 ,”Four”} );

cout<<endl ;
for(auto elem:mp)
cout<< elem.first << ” ” << elem.second << endl;


5 Five

3 three
4 Four
5 Five
89 Eighty-nine

So a pair element with key as 4 is inserted before the element with key as 5.

Link:map::insert function

Here is another example where the key passed is larger than any of the key of the elements of the container.

Code example

map<int,string>::iterator it1=mp.lower_bound(90); ///end() is returned

cout<< it1->first << ” ” << it1->second << endl;

The output is a garbage value.


Stop wasting time,earn money($$$) from your website-Join Now!