If I have an vector of unsigned char's, what's the best way to pass them to a function that only takes a vector of char's? What about a vector of signed chars?
In the conversion, is there any risk of losing data?
This is a discussion on Best way to convert std::vector<unsigned char> to std::vector<char>? within the C++ Programming forums, part of the General Programming Boards category; If I have an vector of unsigned char's, what's the best way to pass them to a function that only ...
If I have an vector of unsigned char's, what's the best way to pass them to a function that only takes a vector of char's? What about a vector of signed chars?
In the conversion, is there any risk of losing data?
You have to copy the data to a vector of signed chars. There's no good way to just twiddle the type. However, there is no risk of data loss. Only the type changes -- the bit patterns remain the same.
A custom vector class could be written that allows magical conversion to and from signed or unsigned, but you can't do it with std::vector<T>
But then, seeing as it only differs by type, hoe about casting it to an appropriate vector type? If it's in the signed range, it should be fine, but I'm guessing it's sort of undefined behavior...
For information on how to enable C++11 on your compiler, look here.
よく聞くがいい!私は天才だからね! ^_^
If you can change the function that you want to pass to, how about making it templated?
Otherwise, how about using a vector of char to begin with?
I might be wrong.
Quoted more than 1000 times (I hope).Thank you, anon. You sure know how to recognize different types of trees from quite a long way away.
Thanks. So I can't do the following?
Code:std::vector<char> newOne = std::vector<char>( oldUnsignedCharVector.begin(), oldUnsignedCharVector.end() );
That should be okay, since each individual unsigned char element is type cast to char, not the whole std::vector<unsigned char> being type cast to std::vector<char>. In other words, you are copying the data to a vector of chars.So I can't do the following?
C + C++ Compiler: MinGW port of GCC
Version Control System: Bazaar
Look up a C++ Reference and learn How To Ask Questions The Smart Way
All the buzzt!
CornedBee
"There is not now, nor has there ever been, nor will there ever be, any programming language in which it is the least bit difficult to write bad code."
- Flon's Law