gpt4 book ai didi

c++11 - 获取最接近 double std::vector 中的值的项目

转载 作者:行者123 更新时间:2023-12-02 18:41:19 24 4
gpt4 key购买 nike

C++ 11 中是否有一种优雅的方法可以从最接近某个值的 doublestd::vector 中获取项目?

代码:

#include <iostream>
#include <vector>

double GetClosest(const std::vector<double>& vec, double value) {
// How to get the item closest to "value" from the items in vec. Vec is assumed to be sorted.
}

int main() {
std::vector<double> my_doubles_vec;
my_doubles_vec.push_back(101480.76915103197);
my_doubles_vec.push_back(101480.85708367825);
my_doubles_vec.push_back(101480.93293087184);
my_doubles_vec.push_back(101481.0027936101);
my_doubles_vec.push_back(101481.5625);
my_doubles_vec.push_back(101481.5626);


std::cout.precision(17);
std::cout << GetClosest(my_doubles_vec, 101480.76915103201) << std::endl; // Should output "101480.76915103197"
std::cout << GetClosest(my_doubles_vec, 101480.93293086279) << std::endl; // Should output "101480.93293087184"
std::cout << GetClosest(my_doubles_vec, 101481.5625) << std::endl; // Should output "101481.5625"

return 0;
}

由于它是 doublestd::vector,我认为精度会发挥作用?或者逻辑是否可以以一种不需要担心精度的方式构建?

最佳答案

您可以使用std::partition_point , std::lower_boundstd::upper_bound在排序范围内。

示例:

#include <algorithm>
#include <cmath>
#include <stdexcept>

double GetClosest(const std::vector<double>& vec, double value) {
if(vec.empty()) throw std::runtime_error("no elements");

// partition_point is the most generic of the three:
auto it = std::partition_point(vec.begin(), vec.end(), [value](double v) {
return v < value;
});
// or auto it = std::lower_bound(vec.begin(), vec.end(), value);
// or auto it = std::upper_bound(vec.begin(), vec.end(), value);

if(it == vec.end()) --it; // value larger than the largest in the vector
else if( it != vec.begin()) { // value not less than first
// check which one of the two around the partition point that is closest
if(std::abs(*std::prev(it) - value) < std::abs(*it - value)) --it;
}

return *it;
}

关于c++11 - 获取最接近 double std::vector 中的值的项目,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/67977046/

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