C & C++

C & C++

Made by DeepSource

Use of inefficient generic algorithm over efficient container based ones CXX-P2000

Performance
Major

Algorithms inside the associative containers have more efficient implementations than standard linear search, as they make use of efficient key-retrieval methods present to locate the elements. So while the standard algorithm uses std::iterator base and has a linear complexity of O(n) even when used on the associative containers, most internal methods of associative containers would have sub-linear time complexity.
std::set::find is more expressive and easier to read than std::find when used with a set. It makes it clear that you are searching for an element in a set, rather than in some arbitrary range.

The following search algorithms

  • std::find
  • std::count
  • std::equal_range
  • std::lower_bound
  • std::upper_bound

are less efficient when used on key-based containers associative containers

For better performance use the methods implemented by associative containers. For example, use std::set::find rather then std::find.

Bad practice

std::set<int> S{1, 2, 3};
auto result = std::find(S.begin(), S.end(), 2);

std::unordered_map<int, int> M{{1, 2}, {2, 1}};
auto result = std::find(M.begin(), M.end(), std::pair<const int, int>{1, 2});

Recommended

std::set<int> S{1, 2, 3};
auto result = S.find(2);

std::unordered_map<int, int> M{{1, 2}, {2, 1}};
auto result = M.find(1); // doesn't need value type to match