• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 // Copyright 2021 The Chromium Authors
2 // Use of this source code is governed by a BSD-style license that can be
3 // found in the LICENSE file.
4 
5 #ifndef BASE_CONTAINERS_CXX20_ERASE_VECTOR_H_
6 #define BASE_CONTAINERS_CXX20_ERASE_VECTOR_H_
7 
8 #include <algorithm>
9 #include <iterator>
10 #include <vector>
11 
12 namespace base {
13 
14 // Erase/EraseIf are based on C++20's uniform container erasure API:
15 // - https://eel.is/c++draft/libraryindex#:erase
16 // - https://eel.is/c++draft/libraryindex#:erase_if
17 // They provide a generic way to erase elements from a container.
18 // The functions here implement these for the standard containers until those
19 // functions are available in the C++ standard.
20 // Note: there is no std::erase for standard associative containers so we don't
21 // have it either.
22 
23 template <class T, class Allocator, class Value>
Erase(std::vector<T,Allocator> & container,const Value & value)24 size_t Erase(std::vector<T, Allocator>& container, const Value& value) {
25   auto it = std::remove(container.begin(), container.end(), value);
26   size_t removed = static_cast<size_t>(std::distance(it, container.end()));
27   container.erase(it, container.end());
28   return removed;
29 }
30 
31 template <class T, class Allocator, class Predicate>
EraseIf(std::vector<T,Allocator> & container,Predicate pred)32 size_t EraseIf(std::vector<T, Allocator>& container, Predicate pred) {
33   auto it = std::remove_if(container.begin(), container.end(), pred);
34   size_t removed = static_cast<size_t>(std::distance(it, container.end()));
35   container.erase(it, container.end());
36   return removed;
37 }
38 
39 }  // namespace base
40 
41 #endif  // BASE_CONTAINERS_CXX20_ERASE_VECTOR_H_
42