Mac_P
Mac_P

Reputation: 35

Find closest value in a vector of struct

I'm looking for solution how to find the most similar value in a vector of struct:

struct tStruct{
    int nr;
    double data1;
    double data2;};

vector<tStruct> tPoint {
    {3, 32.3247351, 14.6209107},
    {4, 32.3262635, 14.6352101},
    {5, 32.3249088, 14.6497090},
    {6, 32.3240278, 14.6642700},
    {7, 32.3256065, 14.6786958}};

I have two variables double vdata1 = 32.32443, double vdata2 = 14.65692 that I would like compare with tPoint vector and return the nearest found value, e.g. {5, 32.3249088, 14.6497090} to make some other calculations.

Is there any way to achieve this?

Upvotes: 0

Views: 419

Answers (2)

Ap31
Ap31

Reputation: 3324

Of course there is a way, usually you would do something like that:

tStruct result = tPoint.front(); //Assuming there is always at least one point
auto d = distance(result); // distance() is what you define it to be
for(const auto& point : tPoint)
{
    auto current_distance = distance(point);
    if(current_distance < d)
    {
         d = current_distance; 
         result = point;
    }
}

This is pretty much what std::min_element does, but I'm not sure it can cache distances, so it would be a bit less effective. Probably it can be done as a combination of std::min_element and boost::transform_iterator.

Upvotes: 3

lubgr
lubgr

Reputation: 38315

I would suggest using std::min_element that ships with the <algorithm> header and pass a custom predicate. This way, the actual notion of what "closest" means can be kept in a function object. An exemplary snippet could look like this:

#include <algorithm>
#include <cmath>

double vdata1 = 32.32443;
double vdata2 = 14.65692;

const auto dist = [vdata1, vdata2](const auto& p){
    // Change the following to your needs
    return std::pow((p.data1 - vdata1), 2) + std::pow((p.data2 - vdata2), 2);
};

const auto closest = std::min_element(tPoint.cbegin(), tPoint.cend(),
        [&dist](const auto& p1, const auto& p2){ return dist(p1) < dist(p2); });

Upvotes: 2

Related Questions