如何删除矢量中的重复值,最后一个除外

How can i delete duplicate value in vector except last one

本文关键字:最后一个 何删除 删除      更新时间:2023-10-16

我在向量中有一组坐标(x,y,z(值,其中第一个值和最后一个值应该相同,但向量中还有另一个坐标,该坐标对于向量中的第一个和最后一个元素也很常见。 我想在不更改顺序的情况下删除矢量中的重复元素。

下面是我的矢量。

std::vector<std::vector<mi::math::Vector_struct<mi::Float32, 3> >> points;

如果我理解你的问题没错,你是说:

  • 向量中的第一个和最后一个元素相等。
  • 您希望删除这两者之间等于它们的所有元素。

如果是这种情况,您可以使用标准的删除+擦除习惯用法,但调整边界:

// We need at least two elements to safely manipulate the iterators like this, and
// while we're testing the size we might as well make sure there's at least one
// element that could be removed.
if (points.size() >= 3) {
// Removes all elements between the first and last element that are equal to
// the first element.
points.erase(
std::remove(points.begin() + 1, points.end() - 1, points.front()),
points.end() - 1
);
}

确保你#include <algorithm>得到std::remove()


请注意,此代码正在比较外部向量。 如果要在每个内部向量上运行它,只需这样做(遍历points并将此代码应用于每个内部向量(。 如果您需要删除多个内部向量中的重复项,请详细说明您的问题。