17.5 Algorithms Library

17.5.1 Do not ignore the result of std::remove, std::remove_if or std::unique

The mutating algorithms std::remove, std::remove_if and both overloads of std::unique operate by swapping or moving elements of the range they are operating over. On completion, they return an iterator to the last valid element. In the majority of cases the correct behavior is to use this result as the first operand in a call to std::erase.

#include <vector>
#include <algorithm>
#include <iostream>
#include <cstdint>
                                                       
int main ()
{
std::vector<int32_t> v1 = { 0, 0, 1, 1, 2, 2, 3, 3, 4, 4 };
std::unique(v1.begin(), v1.end ());                       // @@- Non-Compliant -@@
                 
// The possible contents of the vector are:
// { 0, 1, 2, 3, 4, 2, 3, 3, 4, 4 };
                   
std::vector<int32_t> v2 = { 0, 0, 1, 1, 2, 2, 3, 3, 4, 4 };
v2.erase (std::unique(v2.begin(), v2.end ()), v2.end ()); // @@+ Compliant +@@
}

References

  • MISRA C++:2008 – 0-1-7

Click here for references