c++ - Map a range of values to a single value -
i need map values ranging between lowerbound , upperbound value.
illustrative example:
for example, imagine have gps system has users subscribed it. system able provide me distance of user point. based on distance of user want assign them id.
thus users in distance
1100id: 8.4101200id: 7.2201300id: 3.6401600id: 4.1
and on...
my approach:
so did, created std::map initializing follows:
std::map<int, double> distancetoidmap; distancetoidmap = { {100, 8.4}, {200, 7.2}, {300, 3.6}, }; then use code id given distance:
double rounduptohundred = std::ceil(realdistance / 100.0) * 100; double powerfordistance = distancetoidmap.at(rounduptohundred); however approach breaks down 401 600 distance, because ceiling nearest hundred distance of 400+ value 500 don't have entry in map. of course trivial solution add entry 500 distancetoidmap not how want handle problem.
i have map {(lowerbound, upperbound) , correspondingid} structure can address cases id covers distance spanning more 100m. , given can check if lowerbound < realdistance < upperbound , provide id.
it sounds use case std::lower_bound. note lower_bound correct implementation, not upper_bound. code compiles , works. map not need sorted, sorted. should run in o(log(n)).
you'll need catch exception...
#include <iostream> #include <algorithm> #include <map> #include <stdexcept> using namespace std; std::map<int, double> distancetoidmap = { {100, 8.4}, {200, 7.2}, {300, 3.6}, {600, 4.1} }; double distance(int user) { auto x = std::lower_bound(distancetoidmap.begin(), distancetoidmap.end(), std::pair<const int,double>(user,0)); if (x == distancetoidmap.end()) throw std::runtime_error("can't find"); return x->second; } int main() { for(int user=25;user < 650;user+=25) { cout << user << " " << distance(user) << std::endl; } return 0; } output:
sh-4.3# g++ -o main *.cpp -std=c++11 main sh-4.3# main 25 8.4 50 8.4 75 8.4 100 8.4 125 7.2 150 7.2 175 7.2 200 7.2 225 3.6 250 3.6 275 3.6 300 3.6 325 4.1 350 4.1 375 4.1 400 4.1 425 4.1 450 4.1 475 4.1 500 4.1 525 4.1 550 4.1 575 4.1 600 4.1 terminate called after throwing instance of 'std::runtime_error' what(): can't find aborted (core dumped) sh-4.3# main
Comments
Post a Comment