简体   繁体   English

C++ 模板 function 连接 std::vector 和 std::array 类型

[英]C++ template function to concatenate both std::vector and std::array types

I have project where I am working with both fixed and variable length arrays of bytes.我有一个项目,我正在使用固定和可变长度 arrays 字节。 I want to have a function that can concatenate two arbitrary containers of bytes and return a single vector.我想要一个 function 可以连接两个任意字节容器并返回一个向量。 Currently I am using目前我正在使用

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

However, I would like more generic way to do this, which better uses the capabilities of C++.但是,我想要更通用的方法来执行此操作,它可以更好地使用 C++ 的功能。 I do not want to just accept iterators.我不想只接受迭代器。 I am trying to figure out how to accept two arbitrary containers and return a vector containing their contents.我试图弄清楚如何接受两个任意容器并返回一个包含它们内容的向量。 Ideally I would also not like to have to know the type inside the vector.理想情况下,我也不想知道向量内的类型。

Something like就像是

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

I think there is a templated approach to this but I just have not been able to figure it out.我认为有一个模板化的方法,但我只是无法弄清楚。

std::array , std::vector and other contiguous_ranges can be converted to a lightweight std::span , which you can use for type erasure. std::arraystd::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;
}

Demo演示

In general, generic + arbitrary, means templates.一般来说,通用+任意,意味着模板。

Something like this?像这样的东西?

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM