Reputation: 43
I have a vector object that contains clipboard data. I am trying to write the contents of the clipboard data into a temp file using a buffered stream. I am using iterators to access the contents of the vector.
I am running into trouble while trying to convert the clipboard data which is a std::vector ClipboardDataVector
to inbuffer
which of type const std::uint8_t* inBuffer
.
Here is the code that I use
typedef std::vector ClipboardDataVector;
File::WriteBlock(const std::uint8_t* inBuffer, std::uint32_t inBufferSize);
BOOL WriteToTempFile(ClipboardDataVector& clipBoardData) {
std::vector::iterator clipBoardIterator;
clipBoardIterator = clipBoardData.begin();
File::WriteBlock((const uint8_t *)clipBoardIterator, clipBoardData.size());
}
When I compile this code I get the following error.
error C2440: 'type cast' : cannot convert from 'std::_Vector_iterator<_Myvec>' to 'const uint8_t *'
I am new to vectors and I am finding it hard to get my head around this error - how can I resolve it?
Upvotes: 4
Views: 1775
Reputation: 88711
When you use a std::vector
you need to specify the type it holds. So your typedef
needs to be:
typedef std::vector<uint8_t> ClipboardDataVector;
Once you've done that if you have a vector of that type and you want to get a const uint8_t *
the usual idiom is:
void WriteToTempFile(const ClipboardDataVector& clipBoardData) {
const uint8_t *data = clipBoardData.size() ? &clipBoardData[0] : NULL;
// ...
}
This works because vectors have contiguous storage - it's asking for a pointer to the first element in the vector. It also checks for the special case where the vector is empty and so the subscript operator can't be used. This clearly won't work for something like std::list
where the elements aren't always contiguous.
You were on the right sort of track with iterators, but iterators are a generalisation of the concept of a pointer - that is they look and feel like a pointer (by either being a pointer or some operator overloading) but they're not necessarily going to actually be a pointer always. If you need a pointer from a vector (because you're interacting with C usually) then the address of the first element is the safe, portable way to do it.
(I also made the reference to clipBoardData
be const
also - it's a good habit to be in, marking things you won't alter as const
always)
Upvotes: 5