1

我是 C++ 和数据结构的新手,我有近似最近邻居的代码,为此我在 C++ 中实现了一个 Kd-tree。

我的问题如何将 kd-tree 写入文件以及如何从该文件中读取它?

谢谢你的帮助

4

2 回答 2

3

参见boost::serialization。您可以在多种输出格式之间进行选择 - 纯文本、xml、二进制

于 2011-04-24T06:03:08.140 回答
0

If you're new to C++, you just have to understand what exactly do you need and implement it in a correct simple way. So no boost dependency is needed. At first - your kd-tree likely stores pointers to objects and do not own them. 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. Objects that own x, y must have friend correspondent functions

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.

于 2011-04-24T08:02:04.817 回答