   Copying data out of std::vector
  Instead of looping through each element, is this a safe way of copying the data out of a vector?std::vector<T> Data; //pretend this is filled in with dataunsigned int NumData = (unsigned int)Data.size();/*Copy the memory out of the vector */T *TempData = new T[NumData];memcpy(reinterpret_cast<void*>(TempData), reinterpret_cast<void*>(&Data[0]), sizeof(T)*NumData);_Data = reinterpret_cast<void*>(TempData);
  Assuming your data can itself be safely memcpy-ed (no destructor, no virtual functions, no pointers...), yes, it's safe... but overcomplicated.#include <algorithm>std::copy(Data.begin(), Data.end(), TempData);Always does the Right Thing.   ;  Great, thanks fruny!  Types that I'm dealing with are primitive types (int, float, short, etc).  I usually use std::copy but I'm actually passing the data as a byte array to be memcpy'd as needed.  I just wanted to make sure you could safely access the array with &(Data[0]).  Thanks!   ;Quote:Original post by okonomiyakiI just wanted to make sure you could safely access the array with &(Data[0]).Yeah, you can. Vectors are guaranteed to hold a contiguous block of memory. Taking the address of the first element is the correct way to get a pointer that's compatible with a C API.That's the question you should have asked. [smile]   ;Quote:Original post by FrunyQuote:Original post by okonomiyakiI just wanted to make sure you could safely access the array with &(Data[0]).Yeah, you can. Vectors are guaranteed to hold a contiguous block of memory. Taking the address of the first element is the correct way to get a pointer that's compatible with a C API.That's the question you should have asked. [smile]And the brackets are superfluous, thanks to operator precedence. OMG smaller code!   ;  I like &vec.front() when I want a pointer to the front of a vector myself.It removes a magic constant, even if it is just 0.;  It should be noted that niether of those work for vector<bool>. In fact, you can't take the address of any element in a vector<bool> ever, because it's niether a vector nor contains bools!   