Reputation: 13
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.
Upvotes: 0
Views: 2079
Reputation: 87944
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.
Upvotes: 2