简体   繁体   English

将kdtree写入/读取文件

[英]Write/Read a kdtree into a file

I am new to C++ and data structure, I have code to approximate the nearest neighbors, and for that I implemented a Kd-tree in C++. 我是C ++和数据结构的新手,我有代码可以近似最近的邻居,为此,我在C ++中实现了Kd树。

My question how can I write the kd-tree into a file and how to read it from that file? 我的问题是如何将kd-tree写入文件以及如何从该文件读取它?

Thanks for any help 谢谢你的帮助

See boost::serialization . 参见boost :: serialization You may choose between several output formats - plain text, xml, binary 您可以选择几种输出格式-纯文本,xml,二进制

If you're new to C++, you just have to understand what exactly do you need and implement it in a correct simple way. 如果您不熟悉C ++,则只需了解您真正需要什么,然后以正确的简单方式实现它即可。 So no boost dependency is needed. 因此,不需要增强依赖。 At first - your kd-tree likely stores pointers to objects and do not own them. 首先-您的KD树可能存储指向对象的指针,但不拥有它们。 Consider dumping\\loading via structures that actually own objects (that is responsible for their life time), thus avoiding duplicates and leaks. 考虑通过实际拥有对象(负责其生命周期)的结构进行转储\\加载,从而避免重复和泄漏。 At second - usually trees are not stored in files, instead they are constructed each time you load some geometry because they require more storage than just an array of objects and they can contain duplicates, that you need to track separately. 第二,通常树不存储在文件中,而是在每次加载某些几何图形时进行构建,因为它们需要的存储空间不仅仅是对象数组,而且它们可能包含重复项,因此需要分别进行跟踪。 Thereby, if you figured out who owns your objects, your read\\write procedures will look like 因此,如果您找出谁拥有您的对象,则您的读\\写过程将类似于

int main(int argc, char** argv) {
  std::string filename = "geometty_dump.txt"      
  if (argc == 2) {  // filename explicitly provided
    filename = *argv[1];
  }
  ProblemDriver driver; // stores geometry owner\owners
  bool res = driver.GetGeometry(filename);
  if (res) res = driver.SolveProblem();
  if (res) res = driver.DumpGeometry();
  return res;
}

In the place where you access geometric data itself (like double x, y; ) you must include <iostream> , try to read something about C++ i\\o if your question is about it. 在您访问几何数据本身的地方(例如double x, y; ),您必须包括<iostream> ,如果您对此有疑问,请尝试阅读一些有关C ++ i \\ o的内容。 Objects that own x, y must have friend correspondent functions 拥有x,y的对象必须具有好友对应功能

ostream& operator<< (ostream out&, const MyPoint& point) {
  out << point.x() << point.y() << '\n';
}
ostream& operator>> (istream in&, MyPoint& point) {
  double x, y;
  in >> x >> y;
  point.set(x, y);
}

Meaning you create ofstream and ifstream repectively in ProblemDriver methods ( GetGeometry , DumpGeometry ) that invoke these functions. 这意味着您将在调用这些函数的ProblemDriver方法( GetGeometryDumpGeometry )中ProblemDriver创建ofstreamifstream

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM