首页 > 解决方案 > 删除向量c ++的重复元素

问题描述

所以.. 我有 2 个向量:xmax 和 ymax,它们代表点列表的 x 和 y 坐标。我想删除其中 xmax[i]==xmax[i-1] 和 ymax[i]==ymax[i-1] 的变量(所以......总之,我想删除重复的点坐标相同)。这是我正在使用的代码:

std::vector<double> xx, yy;
        for (int i = 0; i < xmax.size(); i++) {
            if (i > 0 && xmax[i] == xmax[i - 1] && ymax[i]==ymax[i-1])
              continue;
            xx.push_back(xmax[i]);
            yy.push_back(ymax[i]);
        }

但我想知道是否有一种简单的方法可以在不为此创建新向量的情况下删除变量。

标签: c++vector

解决方案


我建议切换到成对的单个向量(而不是两个单独的向量):

std::vector<std::pair<int, int>> points = {{1, 1}, {5, 2}, {5, 2}, {7, 10}};

然后你就可以使用std::unique().

如果你定义一个比较器函数:

bool point_compare(const std::pair<int, int> &p1, const std::pair<int, int> &p2) {
    return p1.first == p2.first && p1.second == p2.second;
}

然后你可以std::unique()像这样使用:

auto last = std::unique(points.begin(), points.end());
points.erase(last, points.end());

在此处查看实际操作:https ://ideone.com/fZM9b2


推荐阅读