cxx20_erase_string.h 1.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243
  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_STRING_H_
  5. #define BASE_CONTAINERS_CXX20_ERASE_STRING_H_
  6. #include <algorithm>
  7. #include <iterator>
  8. #include <string>
  9. namespace base {
  10. // Erase/EraseIf are based on C++20's uniform container erasure API:
  11. // - https://eel.is/c++draft/libraryindex#:erase
  12. // - https://eel.is/c++draft/libraryindex#:erase_if
  13. // They provide a generic way to erase elements from a container.
  14. // The functions here implement these for the standard containers until those
  15. // functions are available in the C++ standard.
  16. // Note: there is no std::erase for standard associative containers so we don't
  17. // have it either.
  18. template <typename CharT, typename Traits, typename Allocator, typename Value>
  19. size_t Erase(std::basic_string<CharT, Traits, Allocator>& container,
  20. const Value& value) {
  21. auto it = std::remove(container.begin(), container.end(), value);
  22. size_t removed = std::distance(it, container.end());
  23. container.erase(it, container.end());
  24. return removed;
  25. }
  26. template <typename CharT, typename Traits, typename Allocator, class Predicate>
  27. size_t EraseIf(std::basic_string<CharT, Traits, Allocator>& container,
  28. Predicate pred) {
  29. auto it = std::remove_if(container.begin(), container.end(), pred);
  30. size_t removed = std::distance(it, container.end());
  31. container.erase(it, container.end());
  32. return removed;
  33. }
  34. } // namespace base
  35. #endif // BASE_CONTAINERS_CXX20_ERASE_STRING_H_