查找向量中最近的点 [英] Find nearest points in a vector

查看:138
本文介绍了查找向量中最近的点的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

给定一个具有多个值的排序向量,如下例所示:

Given a sorted vector with a number of values, as in the following example:

std::vector<double> f;
f.pushback(10);
f.pushback(100);
f.pushback(1000);
f.pushback(10000);

我正在寻找最优雅的方式来检索任何双d的两个值,毗邻它。例如,给定值45,我想这返回10和100。

I'm looking for the most elegant way to retrieve for any double d the two values that are immediately adjacent to it. For example, given the value "45", I'd like this to return "10" and "100".

我正在查看lower_bound和upper_bound,但他们没有做我想要的。你可以帮忙吗?

I was looking at lower_bound and upper_bound, but they don't do what I want. Can you help?

编辑:我决定发布我自己的分析器,因为它是一个综合的所有有用的答案,我在这个线程。

I've decided to post my own anser, as it is somewhat a composite of all the helpful answers that I got in this thread. I've voted up those answers which I thought were most helpful.

感谢大家,

Dave p>

Dave

推荐答案

我要发布我自己的anser,并投票给任何帮助我达到它,因为这是我'最终会使用,你们都帮助我得出这个结论。欢迎提供评论。

I'm going to post my own anser, and vote anyone up that helped me to reach it, since this is what I'll use in the end, and you've all helped me reach this conclusion. Comments are welcome.

std::pair<value_type, value_type> GetDivisions(const value_type& from) const
{
    if (m_divisions.empty())
        throw 0; // Can't help you if we're empty.

    std::vector<value_type>::const_iterator it = 
        std::lower_bound(m_divisions.begin(), m_divisions.end(), from);

    if (it == m_divisions.end())
        return std::make_pair(m_divisions.back(), m_divisions.back());
    else if (it == m_divisions.begin())
        return std::make_pair(m_divisions.front(), m_divisions.front());
    else
        return std::make_pair(*(it - 1), *(it));
}

这篇关于查找向量中最近的点的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆