Home > Software design >  Fastest way to transfer/copy data from float* to vector<float>
Fastest way to transfer/copy data from float* to vector<float>

Time:04-06

I have a float* variable. I want to copy the value in the float* to the vector . Could you suggest the fastest way to do it on C ? This is my baseline code

std::vector<float> CopyFloat2Vector(float* input, int size1) {
  std::vector<float> vector_out;
  for (int i = 0; i < size1; i  ) {  
    vector_out.push_back(input[size1   i]);    
  }
  return vector_out;
}

I also tried memcopy but it does not work

float* input =....; //I have some value store in input with size of 1xsize1
std::vector<float> vector_out;
memcpy(vector_out.data(), input, size1 * sizeof(float));

CodePudding user response:

std::vector has a constructor for that. I would assume the standard library implementation will make use of as much optimization as it can in that:

std::vector<float> CopyFloat2Vector(float* input, int size1) {
    return {input, input size1};
}
  • Related