1 // Copyright 2023 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_TEST_TO_VECTOR_H_ 6 #define BASE_TEST_TO_VECTOR_H_ 7 8 #include <functional> 9 #include <iterator> 10 #include <type_traits> 11 #include <utility> 12 #include <vector> 13 14 #include "base/ranges/algorithm.h" 15 #include "base/template_util.h" 16 17 namespace base::test { 18 19 // A handy helper for mapping any container into an std::vector<> with respect 20 // to the provided projection. The deduced vector element type is equal to the 21 // projection's return type with cv-qualifiers removed. 22 // 23 // In C++20 this is roughly equal to: 24 // auto vec = range | views:transform(proj) | ranges::to<std::vector>; 25 // 26 // Complexity: Exactly `size(range)` applications of `proj`. 27 template <typename Range, typename Proj = std::identity> 28 auto ToVector(Range&& range, Proj proj = {}) { 29 using ProjectedType = 30 std::invoke_result_t<Proj, decltype(*std::begin(range))>; 31 std::vector<base::remove_cvref_t<ProjectedType>> container; 32 container.reserve(std::size(range)); 33 base::ranges::transform(std::forward<Range>(range), 34 std::back_inserter(container), std::move(proj)); 35 return container; 36 } 37 38 } // namespace base::test 39 40 #endif // BASE_TEST_TO_VECTOR_H_ 41