cxx20_erase_vector.h 1.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041
  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_VECTOR_H_
  5. #define BASE_CONTAINERS_CXX20_ERASE_VECTOR_H_
  6. #include <algorithm>
  7. #include <iterator>
  8. #include <vector>
  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 <class T, class Allocator, class Value>
  19. size_t Erase(std::vector<T, Allocator>& container, const Value& value) {
  20. auto it = std::remove(container.begin(), container.end(), value);
  21. size_t removed = static_cast<size_t>(std::distance(it, container.end()));
  22. container.erase(it, container.end());
  23. return removed;
  24. }
  25. template <class T, class Allocator, class Predicate>
  26. size_t EraseIf(std::vector<T, Allocator>& container, Predicate pred) {
  27. auto it = std::remove_if(container.begin(), container.end(), pred);
  28. size_t removed = static_cast<size_t>(std::distance(it, container.end()));
  29. container.erase(it, container.end());
  30. return removed;
  31. }
  32. } // namespace base
  33. #endif // BASE_CONTAINERS_CXX20_ERASE_VECTOR_H_