C++:比较数据文件中的点集

C++: Comparing sets of points in a data file

本文关键字:点集 文件 数据 比较 C++      更新时间:2023-10-16

我有一个由三列组成的数据文件,x、y和z(这些是数字)。我想做以下事情:

  1. 比较数据中的每个(x,y)集
  2. 如果两个集合相等,比如(x1,y1)=(x2,y2)
  3. 然后,比较z1和z2。根据比较情况,我会写一个条件,我想覆盖其中一个集,这样它就取通过我所做的一些条件的那个集的值

数据包含数千个点,所以我不确定如何有效地进行比较,以及如何覆盖或忽略未通过该条件的点。

所以,有人能提出一些建议吗例如,在我只有两个点(x1,y1,z1)和(x2,y2,z2)的情况下。

由于您想将所有点与所有其他点进行比较,因此可以执行如下算法。假设数据结构如下:

struct Data {
    double x_, y_, z_;
    bool skip;
    const std::pair<double, double> & xy () const {
        return std::pair<double, double>(x, y);
    }
};
std::vector<Data> file;
typedef std::multimap<std::pair<double, double>, unsigned> PointMap;
PointMap xyline;

然后在读取文件时,搜索xyline以查看当前点是否已经存在。如果是,请相应地更新当前点和file矢量(因为您知道所有匹配点的行号,所以您可以修改所有匹配项,也可以只修改最新的匹配项,由您选择)。然后插入与当前行关联的当前点,然后迭代到文件中的下一行。

文件处理完毕后,写出file的内容。然后,如果您愿意,可以使用输出替换现有文件。

void update (PointMap::iterator first, PointMap::iterator last, Data &d) {
    //... revisit all matching points and decide which to keep
}
Data d;
std::ifstream ifile;
std::ofstream ofile;
ifile.open("input.dat");
while (ifile >> d.x_ >> d.y_ >> d.z_) {
    PointMap::iterator i = xyline.find(d.xy());
    if (i != xyline.end()) {
        update(i, xyline.upper_bound(d.xy(), d);
    }
    xyline.insert(i, std::pair<d.xy(), file.size());
    file.push_back(d);
}
ofile.open("output.dat");
for (size_t i = 0; i < file.size(); ++i) {
    d = file[i];
    if (!d.skip)
        ofile << d.x_ << " " << d.y_ << " " << d.z_ << "n";
}
typedef std::map<float, float> Leafs;
typedef std::map<float, Leafs> Node;
Node root;

以这种方式填充树:假设你想添加(a,b,c)

Leafs l;
l[ b ] = c;
root[ a ] = l;

然后,当添加新值时,使用find(检查std::map::find方法描述)方法来检查值是否存在。这应该是这个"问题"的足够快的解决方案