Bitcoin ABC 0.32.4
P2P Digital Currency
vector.h
Go to the documentation of this file.
1// Copyright (c) 2019 The Bitcoin Core developers
2// Distributed under the MIT software license, see the accompanying
3// file COPYING or http://www.opensource.org/licenses/mit-license.php.
4
5#ifndef BITCOIN_UTIL_VECTOR_H
6#define BITCOIN_UTIL_VECTOR_H
7
8#include <functional>
9#include <initializer_list>
10#include <optional>
11#include <type_traits>
12#include <vector>
13
21template <typename... Args>
22inline std::vector<typename std::common_type<Args...>::type>
23Vector(Args &&...args) {
24 std::vector<typename std::common_type<Args...>::type> ret;
25 ret.reserve(sizeof...(args));
26 // The line below uses the trick from
27 // https://www.experts-exchange.com/articles/32502/None-recursive-variadic-templates-with-std-initializer-list.html
28 (void)std::initializer_list<int>{
29 (ret.emplace_back(std::forward<Args>(args)), 0)...};
30 return ret;
31}
32
34template <typename V> inline V Cat(V v1, V &&v2) {
35 v1.reserve(v1.size() + v2.size());
36 for (auto &arg : v2) {
37 v1.push_back(std::move(arg));
38 }
39 return v1;
40}
41
43template <typename V> inline V Cat(V v1, const V &v2) {
44 v1.reserve(v1.size() + v2.size());
45 for (const auto &arg : v2) {
46 v1.push_back(arg);
47 }
48 return v1;
49}
50
52template <typename V> inline void ClearShrink(V &v) noexcept {
53 // There are various ways to clear a vector and release its memory:
54 //
55 // 1. V{}.swap(v)
56 // 2. v = V{}
57 // 3. v = {}; v.shrink_to_fit();
58 // 4. v.clear(); v.shrink_to_fit();
59 //
60 // (2) does not appear to release memory in glibc debug mode, even if
61 // v.shrink_to_fit() follows. (3) and (4) rely on
62 // std::vector::shrink_to_fit, which is only a non-binding request.
63 // Therefore, we use method (1).
64
65 V{}.swap(v);
66}
67
68template <typename V, typename L>
69inline std::optional<V> FindFirst(const std::vector<V> &vec, const L fnc) {
70 for (const auto &el : vec) {
71 if (fnc(el)) {
72 return el;
73 }
74 }
75 return std::nullopt;
76}
77
78#endif // BITCOIN_UTIL_VECTOR_H
V Cat(V v1, V &&v2)
Concatenate two vectors, moving elements.
Definition: vector.h:34
std::optional< V > FindFirst(const std::vector< V > &vec, const L fnc)
Definition: vector.h:69
std::vector< typename std::common_type< Args... >::type > Vector(Args &&...args)
Construct a vector with the specified elements.
Definition: vector.h:23
void ClearShrink(V &v) noexcept
Clear a vector (or std::deque) and release its allocated memory.
Definition: vector.h:52