简体   繁体   English

是否可以将向量移动到不同类型的向量中?

[英]Is it possible to move a vector into a vector of different type?

Assume, I have two functions that work with arguments that are vectors of different types:假设,我有两个与 arguments 一起使用的函数,它们是不同类型的向量:

void foo(const std::vector<SomeType>& v);
void bar(const std::vector<std::byte>& v);

What if in some place of my code I want to pass the same vector object to both of these functions?如果在我的代码的某个地方我想将相同的向量 object 传递给这两个函数怎么办? Obviously, I cannot just cast a vector of one type to a vector of different type, so I have to create a second vector:显然,我不能只将一种类型的向量转换为不同类型的向量,所以我必须创建第二个向量:

const std::vector<SomeType> v(...);
foo(v);
// v is not needed anymore
const auto vSizeBytes = v.size() * sizeof(SomeType);
std::vector<std::byte> v2;
v2.resize(vSizeBytes);
std::memcpy(&v2[0], &v[0], vSizeBytes);
bar(v2);

But if I know for sure that v is not needed anymore after calling foo(v) , I want move instead of copy.但是如果我确定在调用foo(v) v不再需要 v ,我想要移动而不是复制。 Is there any alternative to std::memcpy() for moving the original data of a container into another container instead of copying it?是否有任何替代std::memcpy()用于将容器的原始数据移动到另一个容器而不是复制它?

You can use templates.您可以使用模板。 Assuming the code in the function will work on both types.假设 function 中的代码适用于这两种类型。

template<class SOMETYPE> void foo(const std::vector<SOMETYPE>& v);
template<class SOMETYPE> void bar(const std::vector<SOMETYPE>& v);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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