c++ typecast array
#include <algorithm>
#include <iostream>
#define N 50
int main() {
int intArray[N] = { ... };
float floatArray[N];
std::copy(intArray, intArray + N, floatArray);
std::cout
<< std::boolalpha << std::equal(intArray, intArray + N, floatArray)
<< std::endl;
return 0;
}
IMO, Use tranform and convert int vector to float vector.
float convert (int i) { return static_cast<float>(i); }
int main () {
int first[10];
float second[10];
// set some values:
for (int i=0; i<10; i++)
first[i] = (i*10);
transform (first, first + 10, second, convert);
return 0;
}
If you use vectors instead of arrays you can then use the iterator in the constructor of the vector to do the copy.
std::vector<int> vi;
vi.push_back(1);
vi.push_back(2);
vi.push_back(3);
std::vector<float> vf(vi.begin(), vi.end());
assert(vf.size() == 3);
If you have as input an array, but you can have as output a vector, you could also do this:
int ai[] = {1,2,3};
std::vector<float> vf(ai, ai+3);
assert(vf.size() == 3);
If you need as input and output an array, you can use std::copy
, but just make sure your output array is big enough:
int ai[] = {1,2,3};
float af[] = {0, 0, 0};
std::copy(ai, ai+3, af);
Note: std::copy
, and the vector constructor will not blindly copy the memory, it will implicitly cast between the 2 types for each element. It performs the assignments *result = *first, *(result + 1) = *(first + 1), and so on...
If you have an array of int
s, what you basically have is a block of N int
s stored contiguously in memory. An array of floats, however, would be N floats stored contiguously in memory, i.e. an entirely different sequence of bits in memory. Additionally, floating point values are represented in binary in an entirely different way than integral values. In fact, you can't even be sure that an int
is the same size as a float.
So therefore, you either have to cast each int
to a float
separately as you process the array, or else create an entirely different array by copying the original array.
For example, you could simply convert each int to a float lazily as you process the array:
int array[100];
// ... fill array with some values
for (int i = 0; i < 100; ++i)
{
float f = array[i]; // implicit conversion here
// now do something with this float
}