# finding a position in stl map

This is a discussion on finding a position in stl map within the C++ Programming forums, part of the General Programming Boards category; hi, i am looking for a function in STL that does this job: say, i have a map with elements ...

1. ## finding a position in stl map

hi,

i am looking for a function in STL that does this job:

say, i have a map with elements a,b,d,e, and their values are 10,20, 30,40 respectively.

i want a method, that gives me 20(or the position of "b") when i enter "c". i mean it finds the biggest element that has a key smaller than or equal to "c".

another example
a,b,c,d, and their values are 10,20, 30,40

i want position of c, or 30; when i enter c

another one:

a,b,c,d, and their values are 10,20, 30,40

i want position of d, or 40; when i enter e

i think lower_bound, upper_bound may work out but i couldnt get them work. can you help me please?

thanks

2. If the values are in the same sorted order as the keys, you could find the key and get to the previous key value with the iterator's decrement operator (first element is an exception).

If they are not in the same order, lower and upper bound might not help (reading their description they seem to be meant for finding the beginning and end of a range of equal values). You might write a function that iterates the map and keeps track of the maximum value below some value. (I'm not too good with algorithm, may-be some of them might work for you - e.g max_element with a custom predicate. But then may-be a map isn't a good choice...)

3. Yes, I believe lower_bound() is the right function.
If you post the code you've tried, it would help us to figure out where the problem is.

Chapter 85. Use the right STL search algorithm:
http://www.ubookcase.com/book/Addiso...5lev1sec2.html

Chapter 86. Use the right STL sort algorithm:
http://www.ubookcase.com/book/Addiso...6lev1sec2.html

4. While that is my favorite C++ book and I would recommend that any C++ programmer buy it, I wonder if that site is legal.

Popular pages Recent additions