2

I have an simple array [not vector] of data ranging between 0-255 in a uchar type array. But for some computation I need to copy the array to a double type array.

I can do that by a loop and copying it element by element. But looking if there is an easy process to do this by some function or methods.

Kousik
  • 465
  • 3
  • 15
  • It really depends on how you intend to convert your bytes to doubles. There's no single way to do that. You might want to look at `memcpy` however, it might do what you need. – john Apr 10 '19 at 09:41
  • 3
    It might help if you posted your 'copying it element by element' code. Then it would be clearer what you are trying to achieve, – john Apr 10 '19 at 09:43
  • I'd suggest `std::copy` or `std::transform` depending on how you want to convert values from char to double. – magras Apr 10 '19 at 09:43
  • 1
    C or C++? The answer will differ fundamentally depending on the language. – Konrad Rudolph Apr 10 '19 at 09:44
  • @KonradRudolph I am doing it in C++11 – Kousik Apr 10 '19 at 09:45
  • @KonradRudolph Even in C++, it is not always a `std::vector` by any means (even in C++ containers, `std::array` for example has no such constructor). `std::copy` or similar solutions are more general. – Fire Lancer Apr 10 '19 at 09:50
  • @FireLancer yes and I am using an simple array thats the issue. – Kousik Apr 10 '19 at 09:54
  • @KonradRudolph I checked the question but there is nothing mentioned for a simple array. – Kousik Apr 10 '19 at 09:54

1 Answers1

2

C++ algorithms work on any type of iterator, they are not restricted to specific container types.

As such, you can use std::copy to copy values from one iterator range to another, and perform implicit type conversion in the process:

uchar a[N];
double b[N];
// …
std::copy(std::begin(a), std::end(a), std::begin(b));
// or:
std::copy_n(std::begin(a), N, std::begin(b));

The above uses a C-style array but the same of course works with std::array.

Konrad Rudolph
  • 530,221
  • 131
  • 937
  • 1,214
  • It's throwing this error. `variable-sized array type ‘long int’ is not a valid template argument` – Kousik Apr 10 '19 at 10:25
  • @KousikMitra How is your array declared? Standard C++ has nothing called “variable-sized array” (these exist as non-standard extensions and shouldn’t be used). It sounds like you should use a vector after all. – Konrad Rudolph Apr 10 '19 at 10:38
  • Thanks. I have used a vector after all and its working fine. Actually I am working with nvcc compiler may be that is the problem with a normal array. – Kousik Apr 10 '19 at 10:46