C++ C4834 error moving from VS2017 to VS2019

Viewed 1153

I am getting this warning, until now I didn't get any warning :

error C2220: the following warning is treated as an error
warning C4834: discarding return value of function with 'nodiscard' attribute

template <typename T>
static void quick_hull(std::vector<T> &points)
{
    points = hull(points);
    // Remove successive duplicates
    std::unique(begin(points), end(points), [](const T &a, const T &b) { return (a.x == b.x) && (a.y == b.y); });
} 
 

Can you please explain why does this happen ?

1 Answers

std::unique does not remove elements. It only reorders them in such a way that all unique values are moved to the front. Then it returns an iterator pointing to the element after the last unique value.

You need this iterator to actually remove the duplicate elements with a container specific method. Without it you don't know where the duplicates start and MSVC warns you, that you are discarding this important return value.

Your code should be

auto new_end = std::unique(begin(points), end(points), ...); // move duplicates to end
points.erase(new_end, end(points)); // actually removes duplicates from vector
Related