简体   繁体   English

如何在C ++中转换不同的数值向量类型

[英]How can I convert different numeric vector type in C++

My question is related to numeric type conversion in C++. 我的问题与C ++中的数字类型转换有关。 A very common way to do that is to use static_cast, for example: 一种非常常见的方法是使用static_cast,例如:

float a;
int b;
a = 3.14;
b = static_cast<int>(a);

Then, how about numeric vector type conversion? 然后,如何进行数字矢量类型转换? Could we continue to use static_cast? 我们可以继续使用static_cast吗? I have done the following experiment: 我做了以下实验:

typedef vector<int> IntVector;
typedef vector<float> FloatVector;
IntVector myvector;
myvector.push_back(3);
myvector.push_back(4);
myvector.push_back(5);

// Solution 1 (successful)
FloatVector solution1 ( myvector.begin(), myvector.end() );
for(int i=0; i<solution1.size(); i++)
   cout<<solution1[i]<<endl;
// Solution 2 (failed)
FloatVector solution2;
solution2 = static_cast<FloatVector> (myvector);

It seems that for numeric vector types it is impossible to use static_cast to convert. 对于数字矢量类型,似乎无法使用static_cast进行转换。 I was wondering whether there are good solutions to this problem. 我想知道这个问题是否有好的解决方案。 Thanks! 谢谢!

您可以使用std :: copy ,因为它执行顺序分配。

You can neither assign nor cast a container with a template parameter T ( std::vector<int> ) into another with a template parameter L ( std::vector<float> ). 您既不能将模板参数为Tstd::vector<int> )的容器分配也不能将其转换为模板参数为Lstd::vector<float> )的容器。 They are different classes after all. 毕竟他们是不同的阶级。

However, since they use iterators you can fill your FloatVector with std::copy : 但是,由于它们使用迭代器,因此可以用 std::copy填充 FloatVector

 
 
 
 
  
  
  FloatVector solution2(myvector.size()); std::copy(myvector.begin(),myvector.end(),solution2.begin());
 
 
  

Edit to address your comment : 编辑发表您的评论

If your current function signature is f(FloatVector) I would recommend you to change it to 如果您当前的函数签名是f(FloatVector) ,建议您将其更改为

template< class T >
ReturnType f(std::vector<T> myVector, ....);

The language directly supports conversion from one numeric type to another. 该语言直接支持从一种数字类型到另一种数字类型的转换。 You do not even need the static_cast , you could just assign. 您甚至不需要static_cast ,只需分配即可。 This conversion involves a logical copying of the value, as opposed to a reinterpretation of the value representation. 这种转换涉及值的逻辑复制,而不是值表示的重新解释。

The language does not directly support conversion between arrays of different types, or for that matter of std::vector of different types. 该语言不直接支持不同类型的数组之间的转换,或者不支持不同类型的std::vector的转换。

But as you found, there is some support for copying elements, and then when each element is numeric, the built-in support for numeric type conversion kicks in for each element. 但是,正如您所发现的,对复制元素有一些支持,然后当每个元素为数字时,每个元素都会获得对数字类型转换的内置支持。

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

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