簡體   English   中英

C++ 模板 function 連接 std::vector 和 std::array 類型

[英]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::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;
}

演示

一般來說,通用+任意,意味着模板。

像這樣的東西?

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