Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Unable to convert a uint8_t vector iterator to a const uint8_t *

Tags:

c++

types

casting

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?

like image 577
Karthik Ramesh Avatar asked Oct 26 '25 06:10

Karthik Ramesh


1 Answers

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)

like image 111
Flexo Avatar answered Oct 28 '25 20:10

Flexo



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!