Search code examples
c++std-ranges

C++ Standard Library algorithms readability


I used to write code in a way that it could be read as plain English.

Can someone give a clue how it is better to read the code below in these terms?

My problem is that the code below reads as “erase all unique elements” while it does quite opposite.

This is not a suggestion to rework STL and ranges somehow, I just curious about some trick in considering/treating std::unique (and some other methods) in this context to make this text less counter-intuitive.

In absence of “not” in the code below (which could help to read as "not unique" or "except unique") what would be the best way to read this code?

std::vector<T> v = …;
std::sort(v.begin(), v.end());
v.erase(std::unique(v.begin(), v.end()), v.end());

Ranges version is not better in these terms:

std::vector<T> v = …;
std::ranges::sort(v);
v.erase(std::ranges::unique(v), v.end());

Solution

  • A very literal transliteration into English would be:

    "Sort v, so the next step has the expected result. From v, erase between the result of unique of v and the end of v"

    Which could be slightly massaged into

    "Erase everything after the unique elements"