gpt4 book ai didi

c++ - 将一系列值映射到单个值

转载 作者:塔克拉玛干 更新时间:2023-11-03 00:10:20 25 4
gpt4 key购买 nike

我需要将 lowerBoundupperBound 之间的值映射到某个值。

示例:

例如,假设我有用户订阅的 GPS 系统。该系统能够为我提供用户与某个点的距离。根据用户的距离,我想为他们分配一个 ID。

因此距离远的用户

  • 1100 得到 ID: 8.4
  • 101200 得到 ID: 7.2
  • 201300 得到 ID: 3.6
  • 401600 得到 ID: 4.1

等等……

我的方法:

所以我做了什么,我通过如下初始化创建了一个 std::map:

   std::map<int, double> distanceToIdMap; 

distanceToIdMap =
{
{100, 8.4},
{200, 7.2},
{300, 3.6},
};

然后我使用此代码获取给定距离的 ID:

double roundUpToHundred = std::ceil(realDistance / 100.0) * 100;
double powerForDistance = distanceToIdMap.at(roundUpToHundred);

然而,我的方法在 401600 的距离上失效了,因为对于 400+ 的距离,我的上限是最近的百位获取我在 map 中没有条目的值 500。当然,简单的解决方案是将 500 的条目添加到 distanceToIdMap 中,但这不是我想要处理此问题的方式。

我想要一个具有 {(lowerbound, upperbound) , correspondingID} 结构的 map ,这样我就可以解决 ID 覆盖距离超过 100 米的情况。给定的可以检查 lowerBound <realDistance <upperBound 然后提供 ID。

最佳答案

这听起来像是 std::lower_bound 的用例.请注意,lower_bound 是正确的实现,而不是 upper_bound。此代码编译并工作。 map 不需要排序,因为它已经排序了。这应该在 O(log(N)) 内运行。

您需要捕获异常...

#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;
}

输出:

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 an instance of 'std::runtime_error'
what(): can't find
Aborted (core dumped)
sh-4.3# main

关于c++ - 将一系列值映射到单个值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30536813/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com