[英]C++ template function to concatenate both std::vector and std::array types
我有一个项目,我正在使用固定和可变长度 arrays 字节。 我想要一个 function 可以连接两个任意字节容器并返回一个向量。 目前我正在使用
std::vector<uint8_t> catBytes(uint8_t const* bytes1, size_t const len1,
uint8_t const* bytes2, size_t const len2) {
std::vector<uint8_t> all_bytes;
all_bytes.reserve(len1 + len2);
all_bytes.insert(all_bytes.begin(), bytes1, bytes1 + len1);
all_bytes.insert(all_bytes.begin() + len1, bytes2, bytes2 + len2);
return all_bytes;
} // catBytes
但是,我想要更通用的方法来执行此操作,它可以更好地使用 C++ 的功能。 我不想只接受迭代器。 我试图弄清楚如何接受两个任意容器并返回一个包含它们内容的向量。 理想情况下,我也不想知道向量内的类型。
就像是
std::vector<unit_8> v1 = { 1, 2, 3, 4 };
std::array<unit_8, 4> a1 = { 1, 2, 3, 4 };
std::array<unit_8, 2> a2 = { 1, 2 };
auto res1 = concat(v1, a1); // std::vector<uint_8> of size 8
auto res2 = concat(a1, a2); // std::vector<uint_8> of size 6
// or
std::vector<char> v2 = { 1, 2, 3, 4 };
std::array<char, 4> a3 = { 1, 2, 3, 4 };
auto res3 = concat(v1, a1); // std::vector<char> of size 8
我认为有一个模板化的方法,但我只是无法弄清楚。
std::array
, std::vector
和其他contiguous_ranges
可以转换为轻量级std::span
,您可以将其用于类型擦除。
#include <cstdint>
#include <span>
#include <vector>
std::vector<uint8_t>
catBytes(std::span<const uint8_t> x, std::span<const uint8_t> y) {
std::vector<uint8_t> all_bytes;
all_bytes.reserve(x.size() + y.size());
all_bytes.insert(all_bytes.begin(), x.begin(), x.end());
all_bytes.insert(all_bytes.end(), y.begin(), y.end());
return all_bytes;
}
一般来说,通用+任意,意味着模板。
像这样的东西?
template<class SizedRange1, class SizedRange2>
auto concat(SizedRange1 const& r1, SizedRange2 const& r2) {
std::vector<typename SizedRange1::value_type> ret;
ret.reserve(r1.size() + r2.size());
using std::begin; using std::end;
ret.insert(ret.end(), begin(r1), end(r1));
ret.insert(ret.end(), begin(r2), end(r2));
return ret;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.