Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Converting a C-string to a std::vector<byte> in an efficient way

Tags:

c++

vector

I want to convert a C-style string into a byte-vector. A working solution would be converting each character manually and pushing it on the vector. However, I'm not satisfied with this solution and want to find a more elegant way.

One of my attempts was the following:

std::vector<byte> myVector;
&myVector[0] = (byte)"MyString";

which bugs and gets me an

error C2106: '=': left operand must be l-value

What is the correct way to do this?

like image 421
Etan Avatar asked Oct 16 '09 18:10

Etan


2 Answers

The most basic thing would be something like:

const char *cstr = "bla"
std::vector<char> vec(cstr, cstr + strlen(cstr));

Of course, don't calculate the length if you know it.

The more common solution is to use the std::string class:

const char *cstr;
std::string str = cstr;
like image 96
GManNickG Avatar answered Nov 14 '22 20:11

GManNickG


STL containers such as vector always take ownership, i.e. they manage their own memory. You cannot modify the memory managed internally by an STL container. For that reason, your attempt (and any similar attempt) is doomed to failure.

The only valid solution is to copy the memory or to write a new STL-style container that doesn’t take ownership of the memory it accesses.

like image 24
Konrad Rudolph Avatar answered Nov 14 '22 21:11

Konrad Rudolph