cxx20_erase_list.h 1.4 KB

1234567891011121314151617181920212223242526272829303132333435363738
  1. // Copyright 2021 The Chromium Authors. All rights reserved.
  2. // Use of this source code is governed by a BSD-style license that can be
  3. // found in the LICENSE file.
  4. #ifndef BASE_CONTAINERS_CXX20_ERASE_LIST_H_
  5. #define BASE_CONTAINERS_CXX20_ERASE_LIST_H_
  6. #include <list>
  7. namespace base {
  8. // Erase/EraseIf are based on C++20's uniform container erasure API:
  9. // - https://eel.is/c++draft/libraryindex#:erase
  10. // - https://eel.is/c++draft/libraryindex#:erase_if
  11. // They provide a generic way to erase elements from a container.
  12. // The functions here implement these for the standard containers until those
  13. // functions are available in the C++ standard.
  14. // Note: there is no std::erase for standard associative containers so we don't
  15. // have it either.
  16. template <class T, class Allocator, class Predicate>
  17. size_t EraseIf(std::list<T, Allocator>& container, Predicate pred) {
  18. size_t old_size = container.size();
  19. container.remove_if(pred);
  20. return old_size - container.size();
  21. }
  22. template <class T, class Allocator, class Value>
  23. size_t Erase(std::list<T, Allocator>& container, const Value& value) {
  24. // Unlike std::list::remove, this function template accepts heterogeneous
  25. // types and does not force a conversion to the container's value type before
  26. // invoking the == operator.
  27. return EraseIf(container, [&](const T& cur) { return cur == value; });
  28. }
  29. } // namespace base
  30. #endif // BASE_CONTAINERS_CXX20_ERASE_LIST_H_