Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I cast `std::string` to `std::vector<unsigned char>` without making a copy?

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?

like image 280
hkBattousai Avatar asked May 16 '13 19:05

hkBattousai


People also ask

How do you pass a string to a vector in C++?

vector <string> a; for(int i =0 ; i < a. size(); i++) { functionA(a[i]); //Error at this line... }

Is vector char a string?

vector is a container, string is a string.


1 Answers

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()));
like image 152
Mark B Avatar answered Sep 21 '22 01:09

Mark B