简体   繁体   中英

Searching a map with upper bound and lower bound

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?

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM