lundi 14 juin 2021

Get item closest to a value in a std::vector of doubles

Is there an elegant way in C++ 11 to get the item from a std::vector of doubles which is closest to a value?

Code:

#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(901480.76915103197);
    my_doubles_vec.push_back(901480.85708367825);
    my_doubles_vec.push_back(901480.93293087184);
    my_doubles_vec.push_back(901481.0027936101);
    my_doubles_vec.push_back(901481.5625);
    my_doubles_vec.push_back(901481.5626);


    std::cout << GetClosest(my_doubles_vec, 901480.76915103201) << std::endl; // Should ouput "901480.76915103197"
    std::cout << GetClosest(my_doubles_vec, 901480.93293086279) << std::endl; // Should ouput "901480.93293087184"
    std::cout << GetClosest(my_doubles_vec, 901481.5625) << std::endl; // Should ouput "901481.5625"

    return 0;
}

Since its a std::vector of doubles, I think precision comes into play? Or can the logic be made in such a way that one doesn't need to bother about precision?

Aucun commentaire:

Enregistrer un commentaire