你能将一个 vector 转换成一个 vector 吗?

huangapple go评论63阅读模式
英文:

Can you cast a vector<int64> to a vector<uint8>

问题

在C++中,将int64_t向量转换为uint8_t的正确方法是什么?

我理解我可以这样做:

std::vector<int64_t> int64Vec;
std::vector<uint8_t> uint8Vec(int64Vec.begin(), int64Vec.end());

但我认为这会创建一个不必要的副本。是否有可能直接转换向量?

原因是uint8vec被传递给一个期望uint8_t向量的函数。

英文:

In C++ what is the correct way to cast a vector of int64_t to uint8_t?

I understand I could to this:

std::vector&lt;int64_t&gt; int64Vec;
std::vector&lt;uint8_t&gt; uint8Vec(int64Vec.begin(), int64Vec.end());

But I think creates an unnecessary copy. Is it possible to cast the vector?

The reason why is that uint8vec is passed to a function which expects a uint8_t vector.

答案1

得分: 3

  • "Is it possible to cast the vector?"

    • 可以将向量进行强制转换吗?
  • "No."

    • 不可以。
  • "The reason why is that uint8vec is passed to a function which expects a uint8_t vector."

    • 原因是 uint8vec 被传递给一个期望 uint8_t 向量的函数。
  • "What should be fixed is that function. If the function would accept iterators instead (that when dereferenced yield a type that can be converted to uint8_t) there would be no issue:"

    • 应该修复的是那个函数。如果该函数接受迭代器(当解引用时产生一个可以转换为 uint8_t 的类型),就不会有问题:
  • "template <typename IT>\nvoid function( IT begin, IT end);"

    • 模板 <typename IT>\nvoid function( IT begin, IT end);"
  • "Perhaps add sanity checks for the type IT to get readable error messages in case IT does not dereference to a type that can be converted to uint8_t."

    • 或许可以为类型 IT 添加健全性检查,以便在 IT 不能解引用为可以转换为 uint8_t 的类型时得到可读的错误消息。
英文:

> Is it possible to cast the vector?

No.

> The reason why is that uint8vec is passed to a function which expects a uint8_t vector.

What should be fixed is that function. If the function would accept iterators instead (that when dereferenced yield a type that can be converted to uint8_t) there would be no issue:

template &lt;typename IT&gt;
void function( IT begin, IT end);

Perhaps add sanity checks for the type IT to get readable error messages in case IT does not dereference to a type that can be converted to uint8_t.

huangapple
  • 本文由 发表于 2020年1月6日 18:31:48
  • 转载请务必保留本文链接:https://go.coder-hub.com/59610483.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定