(2D)Kd树以及最近邻查找算法的实现(递归)
KD-Tree的基本概念就不说了,CSDN网站里很多文章都解释的挺好的
我这里主要关注代码实现和最近邻查找算法的相关代码
参考文章:https://rosettacode.org/wiki/K-d_tree
http://andrewd.ces.clemson.edu/courses/cpsc805/references/nearest_search.pdf
先贴代码
我的代码主要功能是读取csv文件并录入数据,建立kd tree,然后再查找最近点,因为用的是visual studio2019,2017直接复制可能会有问题。
主要和最近邻查找算法有关的,就是NN();
至于递归为什么能成功
说实话
我也不知道。。。。。。。
单纯试出来的。。。
我的kd tree的建立
kdtree.cpp
#include <array>
#include <vector>
#include <iostream>
#include <assert.h>
#include <numeric>
#include <algorithm>
#include <memory>
#include<fstream>
#include <string>
#include <sstream>
#include <stack>
using namespace std;
namespace KDTree
{
double strtodouble(string num) {
double res;
stringstream stream(num);
stream >> res;
return res;
}
using CuttimgDim = char;
struct Point
{
double p[2];
Point(double x = 0, double y = 0) :p{
x,y } {
}
bool operator==(const Point& rp) const
{
return (p[0] == rp[0] && p[1] == rp[1]);
}
double operator[](CuttimgDim c) const
{
assert(c < 2 && c >= 0);
return p[c];
}
static const Point* min(const Point* p1, const Point* p2, CuttimgDim c)
{
if (p1 && p2)
{
if ((*p1)[c] < (*p2)[c])
return p1;
return p2;
}
if (!p1)
return p2;
return p1;
}
static const Point* max(const Point* p1, const Point* p2, CuttimgDim c)
{
if (p1 && p2)
{
if ((*p1)[c] < (*p2)[c])
return p2;
return p1;
}
if (!p1)
return p2;
return p1;
}
};
struct city_info
{
//ascii_name,country name,longitude, latitude, and population
city_info(Point p = Point()) :