0

I am trying to use lower_bound() function which is a built-in function in C++ standard library that returns an iterator pointing to the first element in the container whose key is not considered to go before k. My understanding is that is used as follows:

my_map.lower_bound(key)

I have a class SpeedProfile:

#include <stdio.h>
#include <map>

using namespace std;

class SpeedProfile
{
public:
    map <int, float> timeSlotMap;
};

and I'm trying to call lower_bound from another class:

vector<SpeedProfile> speedProfiles = isRightDirection ? positiveSpeedProfiles : negativeSpeedProfiles; 


time_t t = time(nullptr);
tm* timePtr = localtime(&t);
uint32_t dayOfWeek = timePtr->tm_wday;
SpeedProfile dayProfile = speedProfiles[dayOfWeek];
int secondsPassed = (int) (dateinMillis) / 1000;

float lower_b = dayProfile.timeSlotMap.lower_bound(secondsPassed);

I am getting the following error and I'm not sure how I should proceed.

No viable conversion from 'std::__1::map, std::__1::allocator > >::iterator' (aka '__map_iterator<__tree_iterator, std::__1::__tree_node, void *> *, long> >') to 'float'

Using auto lower_b solves the error warning but I don't think this is the correct way forward.

bolov
  • 72,283
  • 15
  • 145
  • 224
tester345
  • 13
  • 2
  • 1
    You say _returns an iterator_ but write `float lower_b = `. If you want to dereference the iterator to get the `float`, use `->second`. – Useless Aug 26 '19 at 08:52
  • 1
    https://en.cppreference.com/w/cpp/container/map/lower_bound – πάντα ῥεῖ Aug 26 '19 at 08:53
  • [What's the difference between “STL” and “C++ Standard Library”?](https://stackoverflow.com/questions/5205491/whats-the-difference-between-stl-and-c-standard-library) – bolov Aug 26 '19 at 09:28

1 Answers1

2

Well you said it yourself, lower_bound returns a iterator not a float.

To be precise it returns an iterator to the map value type, which is a pair of the key and value (std::pair<int,float> in your case). So to get the float you want you write

float lower_b = dayProfile.timeSlotMap.lower_bound(secondsPassed)->second;

Note this code has undefined behaviour if all the keys are less than secondsPassed. In that case the iterator returned would be to the end of sequence value (i.e. dayProfile.timeSlotMap.end()) and dereferencing that iterator is an error.

john
  • 85,011
  • 4
  • 57
  • 81