【问题标题】:How can i delete duplicate value in vector except last one我如何删除向量中的重复值,除了最后一个
【发布时间】:2020-06-06 05:33:04
【问题描述】:

我在向量中有一组坐标(x,y,z)值,其中第一个值和最后一个值应该相同,但向量中还有另一个坐标,它也与向量中的第一个和最后一个元素共用。我想在不改变顺序的情况下删除向量中的重复元素。

下面是我的矢量。

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

【问题讨论】:

  • this 是否接近您的需要?

标签: c++ c++11 c++14


【解决方案1】:

如果我理解你的问题,你的意思是:

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

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

// 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 &lt;algorithm&gt; 获取std::remove()


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

【讨论】:

    猜你喜欢
    • 2012-11-07
    • 1970-01-01
    • 2012-08-20
    • 1970-01-01
    • 2011-04-14
    • 2022-11-21
    • 1970-01-01
    • 1970-01-01
    • 2023-03-31
    相关资源
    最近更新 更多