There is a library function I want to call whose signature is:
bool WriteBinary(const std::vector<uint8_t> & DataToWrite);
I have an std::string
variable, I want to send it this function as argument.
void WriteString(const std::string & TextData)
{
// ...
WriteBinary(TextData); // <-- How to make this line work?
// ...
}
Is there a way I can directly send the std::string
variable without making a copy of it?
vector <string> a; for(int i =0 ; i < a. size(); i++) { functionA(a[i]); //Error at this line... }
vector is a container, string is a string.
There's no way to do this, because the layouts of the two types are not guaranteed to be similar in any way.
The best approach is to fix WriteBinary
to use "iterators" instead:
bool WriteBinary(const unsigned char* first, const unsigned char* last);
Or template it:
template <typename Iter>
bool WriteBinary(Iter first, Iter last);
And then you can use it for strings, vectors, or any other container you like!
Otherwise you can use the iterator constructor to do the copy as efficiently as possible:
WriteBinary(std::vector<uint8_t>(TextData.begin(), TextData.end()));
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With