简体   繁体   中英

How can I convert different numeric vector type in C++

My question is related to numeric type conversion in C++. A very common way to do that is to use static_cast, for example:

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? 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. 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> ). They are different classes after all.

However, since they use iterators you can fill your FloatVector with std::copy :

 
 
 
 
  
  
  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

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. 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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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