This is a rule that falls into the efficient
subcategory.
Can we have a rule that points out unnecessary calls to std::sort
or std::ranges::sort
? These are unnecessary if they are called on a function local vector(/array/list), and then the only usage of the vector is to access the first or last element. In these cases, the call to sort
should be replaced with a call to std:.ranges::min
or std::ranges::max
, respectively. Alternatively, if the sorted vector is accessed at some other arbitrary index, then nth_element
can still be used instead of sort
.
1 Like
Hi @torgeir.skogen,
I agree that when accessing a specific element is necessary, the call to the sort can be replaced with min
, max
, minmax
(to get two), or nth_element
.
However, as you mentioned this can be effectively determined by the tools only if the container is:
- declared locally in function, or maybe passed as a value parameter,
- not passed to any function (even by const reference),
- only one specific element is accessed
In my experience, I haven’t seen many functions that would meet the above criteria. Of course, these vary between domains and usages. Such a rule would definitely be valuable from the learning perspective.
As this is a request for the new feature (rule), I will transfer this request to PM to collect and record interest in the feature.