Which container can I use to write binary files?

I want to write an array c to the container, and I prefer to modify it if possible. I was thinking about using a vector, but it looks like it has an entry (* pchararray, len); function. The line looked like the next best thing, but it also doesn't have a recording function?

+3
source share
7 answers

Considering

char myarray[10];

You can use STLiterator :

vector <char> v;
copy(myarray, myarray + 10, back_inserter(v));

You can use constructor :

vector <char> v(myarray, myarray + 10);

You can resize and copy :

vector<char> v(10);
copy(myarray, myarray + 10, v.begin());

(and they all work similarly for a string)

Thanks to comments and other answers :)

+7
source

, " " :

char raw_data[100];
std::vector<char> v(raw_data, raw_data + 100);
std::string s(raw_data, raw_data + 100);
+3

. c conatiner, , :

char buf[ n ];
std::vector<char> vc(n); // Thanks to Éric 
std::copy(buf, buf + n, vc.begin()); 
+2

, "",

std::vector<char> charBuffer;

c char (byte)

&charBuffer[0]

.

,

charBuffer.resize(100);
memcpy(&charBuffer[0], src, charBuffer.size());
+1

. , : , , .

std::vector<char> vBuffer;
vBuffer.resize(nLength);
std::copy(pStart, pEnd, &vBuffer[0]);
+1

:

string s( pchararray, len );  // constructor

:

string s;  s.append( pchararray, len ); // append example.

:: insert(), .

('\ 0'), .

See http://www.cplusplus.com/reference/string/string/

+1
source

you should use memcpy in this case (since the vector contains the POD type) using std :: copy, it is faster.

0
source

Source: https://habr.com/ru/post/1703500/


All Articles