algorithm.h 1.3 KB

1234567891011121314151617181920212223242526272829303132333435
  1. // SPDX-FileCopyrightText: Copyright 2019 yuzu Emulator Project
  2. // SPDX-License-Identifier: GPL-2.0-or-later
  3. #pragma once
  4. #include <algorithm>
  5. #include <functional>
  6. // Algorithms that operate on iterators, much like the <algorithm> header.
  7. //
  8. // Note: If the algorithm is not general-purpose and/or doesn't operate on iterators,
  9. // it should probably not be placed within this header.
  10. namespace Common {
  11. template <class ForwardIt, class T, class Compare = std::less<>>
  12. [[nodiscard]] ForwardIt BinaryFind(ForwardIt first, ForwardIt last, const T& value,
  13. Compare comp = {}) {
  14. // Note: BOTH type T and the type after ForwardIt is dereferenced
  15. // must be implicitly convertible to BOTH Type1 and Type2, used in Compare.
  16. // This is stricter than lower_bound requirement (see above)
  17. first = std::lower_bound(first, last, value, comp);
  18. return first != last && !comp(value, *first) ? first : last;
  19. }
  20. template <typename T, typename Func, typename... Args>
  21. T FoldRight(T initial_value, Func&& func, Args&&... args) {
  22. T value{initial_value};
  23. const auto high_func = [&value, &func]<typename U>(U x) { value = func(value, x); };
  24. (std::invoke(high_func, std::forward<Args>(args)), ...);
  25. return value;
  26. }
  27. } // namespace Common