简体   繁体   中英

C++ C4834 error moving from VS2017 to VS2019

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?

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM