C ++ array type

How can I output an int array to a float array? Thanks.

+7
c ++ arrays casting
source share
5 answers
#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; } 
+19
source share

If you have an int s array, then you basically have a block N int , stored permanently in memory. However, an array of floats would be N-floats stored sequentially in memory, i.e. a completely different sequence of bits in memory. In addition, floating point values ​​are represented in binary form completely differently than integer values. In fact, you cannot even be sure that an int is the same size as a float.

Thus, you need to either attach each int to the float separately when processing the array, or create a completely different array by copying the original array.

For example, you can just convert each int to float lazily when you process an 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 } 
+11
source share

If you use vectors instead of arrays, you can use an iterator in the vector constructor to 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 an input array, but you can have a vector as output, you can also do this:

 int ai[] = {1,2,3}; std::vector<float> vf(ai, ai+3); assert(vf.size() == 3); 

If you need to input and output an array, you can use std::copy , but just make sure your output array is large 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 memory, it will implicitly display between the two types for each element . It performs tasks * result = * first, * (result + 1) = * (first + 1) and so on ...

+4
source share

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; } 
+3
source share

You can not.

You will need to create another array and manually copy the elements using a loop.

In C ++, the compiler usually does not put loops in the resulting binary, without explicitly specifying in your code.

+2
source share

All Articles