英文:
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<int64_t> int64Vec;
std::vector<uint8_t> 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 caseIT
does not dereference to a type that can be converted touint8_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 <typename IT>
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
.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论