I want to write a c array into a container and i prefer to modify it if possible. I was thinking of using vector but it does seem to have a write(*pchararray, len); function. String looked like the next best thing but that too doesnt have a write function?
Not sure exactly what you mean with your "write" comment but
std::vector<char> charBuffer;
is functionally equivalent to a c char(byte) array
&charBuffer[0]
gives you the contiguous underlying memory.
So now you can do
charBuffer.resize(100);
memcpy(&charBuffer[0], src, charBuffer.size());
You can use a vector. Preallocate the size and then address the first byte: vectors are guarnateed to be contiguous so this is always valid.
std::vector<char> vBuffer;
vBuffer.resize(nLength);
std::copy(pStart, pEnd, &vBuffer[0]);
Given
char myarray[10];
You can use an STL iterator
:
vector <char> v;
copy(myarray, myarray + 10, back_inserter(v));
You can use a constructor:
vector <char> v(myarray, myarray + 10);
You can resize and copy:
vector<char> v(10);
copy(myarray, myarray + 10, v.begin());
(and all these work similarly for string)
Thanks to comments/other answers :)
Container selection depends on your usage of the individual elements. If you mean copying a c character array to a conatiner, this is what you can use:
char buf[ n ];
std::vector<char> vc(n); // Thanks to Éric
std::copy(buf, buf + n, vc.begin());
Vector, string, and many other containers have a "two iterator" constructor for this purpose:
char raw_data[100];
std::vector<char> v(raw_data, raw_data + 100);
std::string s(raw_data, raw_data + 100);
You can use:
string s( pchararray, len ); // constructor
Or:
string s; s.append( pchararray, len ); // append example.
Or string::insert() if you wanted.
String happily handles null characters ('\0'), provided you specify the length.