[英]C++ How to convert a vector<uint8_t> of size 4 into a 32 bit float
[英]How a convert a vector of float to uint8_t, unit32_t or other datatype?
我想寫一個基於模板的function,它以浮點向量作為輸入,返回基於模板的向量類型。 下面的代碼適用於“int”、“double”、“float”等,但是當我嘗試使用“uint8_t”等數據類型的東西時,我得到了所需大小的向量。 但是當嘗試打印值時,我得到了 empy 行。
#include <iostream>
#include <string>
#include <vector>
template<typename T>
std::vector<T> convertDattype(std::vector<float> float_vec)
{
std::vector<T> vec;
vec.reserve( float_vec.size() ); // avoids unnecessary reallocations
std::transform( float_vec.begin(), float_vec.end(),
std::back_inserter( vec ),
[](const float &arg) { return static_cast<T>(arg); } );
return vec;
}
int main()
{
const uint64_t VEC_COUNT = 10;
std::vector<float> float_vec;
float_vec.reserve(VEC_COUNT);
for (unsigned int i = 0; i < VEC_COUNT; ++i) {
float val = static_cast<float>((rand() % 100) / 3.0f);
float_vec.push_back(val);
}
std::vector<uint8_t> data = convertDatatype<uint8_t>(float_vec);
for(auto a : data) {
std::cout << a << std::endl;
}
}
我不知道std::transform
是否會起作用。 我只想將給定向量的數據類型轉換為T
。 任何幫助,將不勝感激。 謝謝
使用它來轉換向量的數據類型。
intVector = std::vector<uint8_t>(data.begin(), data.end());
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.