C++常用实例1

1.线性拟合获取指定数据对应的值

需求:已知温补表tempCompTable,想通过指定温度值temp,获取对应的温补值value

//打印温补表中的所有数据
    for(auto& entry : tempCompTable)
    {
        printf("(%d, %d) \n", entry.first, entry.second);
}
//查找已知温度值temp对应的键值对iter
auto iter = tempCompTable.find(temp);
//temp在温补表中时,直接使用表中对应的“值”即可
    if(iter != tempCompTable.end())
    {
        value = iter->second;
        printf("TempCompTab have this temperature(%f),channel = %d, compvalue = %f db . %s() \n", temp, channel, value, __func__);
    }
    else//temp不在温补表中时,需要使用线性拟合计算temp对应的温补值
    {
        findClosestPoints(tempCompTable, temp);
        int x1 = g_prevpoint->first;
        int y1 = g_prevpoint->second;
        int x2 = g_nextpoint->first;
        int y2 = g_nextpoint->second;
        value = y1 + (temp- x1) * (y2 - y1) / (x2 - x1);
        printf("Caculate temperature compensation linear value,%s(), channel= %d,  x1 = %d ,y1 = %d, x2 = %d, y2 = %d ,compvalue = %f db. \n", __func__ ,channel, x1, y1, x2, y2, value);
    }

2.查找已知数据临近的数据

lower_bound 是 std::map 提供的一个成员函数,用于在 map 中查找第一个不小于 target_x 的元素。

std::map<int, int>::const_iterator g_prevpoint;
std::map<int, int>::const_iterator g_nextpoint;

void findClosestPoints(const std::map<int, int>& map_data, int target_x)
{
	//查找第一个不小于target_x的元素
    auto it = map_data.lower_bound(target_x);
g_prevpoint = it;
//只要it不是 map中的第一个,g_prevpoint-1就是小于target_x的第一个元素
    if (g_prevpoint != map_data.begin())
    {
        g_prevpoint--;
}
//只要it不是map中的最后一个,it就是大于traget_x的第一个元素
    if (it != map_data.end())
    {
        g_nextpoint = it;
    }
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值