Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Searching a map with upper bound and lower bound

Tags:

STL newbie question:

Regarding functions std::map::upper_bound and std::map::lower_bound is it valid to specify a key that is not actually present in the map?

Example

std::map<int,int> intmap; std::map<int,int>::iterator it1, it2;  intmap[1] = 10; intmap[2] = 20; intmap[4] = 40; intmap[5] = 50;  it1 = intmap.lower_bound (3);  // Is this valid? it2 = intmap.upper_bound (3);  // Is this valid? 
like image 936
NeonGlow Avatar asked Oct 03 '13 11:10

NeonGlow


People also ask

How do you find the upper bound of a map?

map::upper_bound() function is an inbuilt function in C++ STL, which is defined in header file. upper_bound() returns an iterator to the upper bound of the map container. This function returns an iterator which points to the last element which is considered to go after the key k.

Can we use upper bound in map?

Yes, they are both valid. map::lower_bound returns an iterator pointing to the first element that is not less than key. map::upper_bound returns an iterator pointing to the first element that is greater than key.

Can we apply lower bound on map in C++?

map lower_bound() function in C++ STL Parameters: This function accepts a single mandatory parameter key which specifies the element whose lower_bound is to be returned. Return Value: The function returns an iterator pointing to the key in the map container which is equivalent to k passed in the parameter.


1 Answers

Yes, they are both valid.

map::lower_bound returns an iterator pointing to the first element that is not less than key.

map::upper_bound returns an iterator pointing to the first element that is greater than key.

intmap[1]=10; intmap[2]=20; intmap[4]=40;   // <<---both lower_bound(3)/upper_bound(3) will points to here intmap[5]=50; 

lower_bound/upper_bound return the position where value would get inserted.

Note, If you want to check the value key is map or not, you could use std::map::find

like image 106
billz Avatar answered Sep 30 '22 02:09

billz