Abhi
Abhi

Reputation: 15

How can i delete duplicate value in vector except last one

I have a groups of coordinates(x,y,z) value in a vector in which first value and last value should be same but there is another coordinate in vector that is also common to first and last element in vector. i want to delete duplicate element in vector without changing the order.

below is my vector.

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

Upvotes: 0

Views: 99

Answers (1)

cdhowie
cdhowie

Reputation: 169528

If I understand your question right, you are saying that:

  • The first and last elements in the vector are equal.
  • You want to remove all elements between those two that are equal to them.

If that is the case, you can use the standard remove+erase idiom but adjust the bounds:

// 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
    );
}

Make sure you #include <algorithm> to get std::remove().


Note that this code is comparing the outer vectors. If you want to run this over each inner vector, just do that instead (loop over points and apply this code to each inner vector). If you need to remove duplicates across multiple inner vectors, please clarify your question with more details.

Upvotes: 1

Related Questions