diff options
author | Pieter Wuille <pieter.wuille@gmail.com> | 2019-08-28 15:12:51 -0700 |
---|---|---|
committer | Pieter Wuille <pieter.wuille@gmail.com> | 2019-10-16 08:56:57 -0700 |
commit | e65e61c812df90a56e3ce4a8e76c4b746766f387 (patch) | |
tree | 787fa4b641ed0d640f96cf430092961e9d7b1b20 /src/util/vector.h | |
parent | c34b88620dc8435b83e6744895f2ecd3c9ec8de7 (diff) |
Add some general std::vector utility functions
Added are:
* Vector(arg1,arg2,arg3,...) constructs a vector with the specified
arguments as elements. The vector's type is derived from the
arguments. If some of the arguments are rvalue references, they
will be moved into place rather than copied (which can't be achieved
using list initialization).
* Cat(vector1,vector2) returns a concatenation of the two vectors,
efficiently moving elements when relevant.
Vector generalizes (and replaces) the Singleton function in
src/descriptor.cpp, and Cat replaces the Cat function in bech32.cpp
Diffstat (limited to 'src/util/vector.h')
-rw-r--r-- | src/util/vector.h | 51 |
1 files changed, 51 insertions, 0 deletions
diff --git a/src/util/vector.h b/src/util/vector.h new file mode 100644 index 0000000000..dab65ded2a --- /dev/null +++ b/src/util/vector.h @@ -0,0 +1,51 @@ +// Copyright (c) 2019 The Bitcoin Core developers +// Distributed under the MIT software license, see the accompanying +// file COPYING or http://www.opensource.org/licenses/mit-license.php. + +#ifndef BITCOIN_UTIL_VECTOR_H +#define BITCOIN_UTIL_VECTOR_H + +#include <initializer_list> +#include <type_traits> +#include <vector> + +/** Construct a vector with the specified elements. + * + * This is preferable over the list initializing constructor of std::vector: + * - It automatically infers the element type from its arguments. + * - If any arguments are rvalue references, they will be moved into the vector + * (list initialization always copies). + */ +template<typename... Args> +inline std::vector<typename std::common_type<Args...>::type> Vector(Args&&... args) +{ + std::vector<typename std::common_type<Args...>::type> ret; + ret.reserve(sizeof...(args)); + // The line below uses the trick from https://www.experts-exchange.com/articles/32502/None-recursive-variadic-templates-with-std-initializer-list.html + (void)std::initializer_list<int>{(ret.emplace_back(std::forward<Args>(args)), 0)...}; + return ret; +} + +/** Concatenate two vectors, moving elements. */ +template<typename V> +inline V Cat(V v1, V&& v2) +{ + v1.reserve(v1.size() + v2.size()); + for (auto& arg : v2) { + v1.push_back(std::move(arg)); + } + return v1; +} + +/** Concatenate two vectors. */ +template<typename V> +inline V Cat(V v1, const V& v2) +{ + v1.reserve(v1.size() + v2.size()); + for (const auto& arg : v2) { + v1.push_back(arg); + } + return v1; +} + +#endif // BITCOIN_UTIL_VECTOR_H |