Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I do equivalent of memcpy from a raw array to a std::vector?

I have a class that has (amongst many other things) a pointer to unsigned char that gets deleted and reallocated to store some data from another array. This done with a function

 class MyClass {
  private:
      unsigned char* m_Buffer;
      int m_BufferSize;
  public:
      bool SetBuffer(int iSize, const unsigned char* pArray); 
 };

 bool MyClass::SetBuffer(int iSize, const unsigned char* pArray) {
     bool bOK = false;
     if (pArray != NULL  && iSize > 0) {
         delete [] m_Buffer;
         m_Buffer = new unsigned char[iSize];
         memcpy(m_Buffer,pArray,iSize);
         m_BufferSize = iSize;
         bOK = true;
      }
      return bOK;
  }

I dont like this code at all, and I would really like to replace the pointer with a std::vector<unsigned char>. My question is, how would I perform the memcpy aspect? If I were passing a vector in as argument to my function, I could copy it using iterators, but I have no control over parameter argument type so I am stuck with unsigned char* . Is there a way of using iterators, or sizing the vector to the right size and then accessing its internal array so that I can still copy the data with memcpy ? Or even better something using iterators?? I know I could use a loop and push_back but that seems painfully inefficient to me. Any suggestions will be gratefully received.

like image 983
mathematician1975 Avatar asked Aug 20 '12 09:08

mathematician1975


1 Answers

Actually, iterators are modelled from pointers and therefore pointers within an array are considered to implement the RandomAccessIterator concept.

Therefore:

m_buffer.assign(pArray, pArray + Size);
like image 110
Matthieu M. Avatar answered Oct 19 '22 23:10

Matthieu M.