cxx20_erase_list.h (1412B)
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_LIST_H_ 6 #define BASE_CONTAINERS_CXX20_ERASE_LIST_H_ 7 8 #include <list> 9 10 namespace base { 11 12 // Erase/EraseIf are based on C++20's uniform container erasure API: 13 // - https://eel.is/c++draft/libraryindex#:erase 14 // - https://eel.is/c++draft/libraryindex#:erase_if 15 // They provide a generic way to erase elements from a container. 16 // The functions here implement these for the standard containers until those 17 // functions are available in the C++ standard. 18 // Note: there is no std::erase for standard associative containers so we don't 19 // have it either. 20 21 template <class T, class Allocator, class Predicate> 22 size_t EraseIf(std::list<T, Allocator>& container, Predicate pred) { 23 size_t old_size = container.size(); 24 container.remove_if(pred); 25 return old_size - container.size(); 26 } 27 28 template <class T, class Allocator, class Value> 29 size_t Erase(std::list<T, Allocator>& container, const Value& value) { 30 // Unlike std::list::remove, this function template accepts heterogeneous 31 // types and does not force a conversion to the container's value type before 32 // invoking the == operator. 33 return EraseIf(container, [&](const T& cur) { return cur == value; }); 34 } 35 36 } // namespace base 37 38 #endif // BASE_CONTAINERS_CXX20_ERASE_LIST_H_