tags:

views:

630

answers:

6

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?

+6  A: 

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;
GMan
have to use std::vetor<byte> to store it in some binary format.
Etan
A: 
std::vector<byte> myVector;
const char* str = "MyString";
myVector.assign( str, str+strlen(str) );
Kirill V. Lyadvinsky
A: 

The most obvious question would be why you don't just use std::string:

std::string myString("MyString");

but if you really think you need a vector:

char myString[] = "MyString";

std::vector<byte> myVector(myString, myString+sizeof(myString));

You might also want to consider using std::tr1::array:

std::tr1::array<byte, sizeof("MyString")> myArray = {"MyString"};

C++ 0x will also have std::array.

Jerry Coffin
A more obvious question to me is: where does he get the char array from in the first place (unless some library function allocates and returns it)?
UncleBens
+4  A: 

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.

Konrad Rudolph
A: 

Something along these lines should work

 std::vector<byte> myVector = std::vector((byte*)cstring, (byte*)ctring + strlen(cstring))

Also, this is still going to just iterate through the c string and insert the values into the vector. Like Konrad said, that's just how you have to do it since vectors manage their own memory.

Nali4Freedom
A: 

const char *cstr = "bla"

std::vector vec;

vec.resize(strlen(cstr)+1);

strcpy(&vec[0],cstr);

Vivek