您好,登錄后才能下訂單哦!
通常使用vector<char>來存儲二進制數據(比如網絡數據包).因此它會與char* 進行相互轉換,具體方法如下例所示:
#include <iostream>
#include <vector>
#include <iterator>
#include <algorithm>
#include <cstring>
using namespace std;
void printVector(const vector<char>& v){
cout << "vector content : ";
for_each(v.cbegin(), v.cend(), [](const char& val)->void{cout << val; });
cout << endl;
}
int main() {
vector<char> vdata;
const char* in = "test1";
vdata.insert(vdata.end(),in,in+strlen(in));
vdata.insert(vdata.end(),'a');
printVector(vdata);
cout << endl;
char* out = &vdata[0];
cout <<"vector<char> --> char* : "<< out << endl;
out[0] = 'j';//can changes the vector's content
cout <<"vector<char> --> char* after change content: "<< out << endl;
printVector(vdata);
cout << endl;
cout <<"get copied char* from vector<char>..."<<endl;
char *buffer = new char[vdata.size()];
std::copy(vdata.begin(), vdata.end(), buffer);
cout <<"vector<char> --> char* : "<< buffer << endl;
buffer[0] = 'z';//can changes the vector's content
cout << "vector<char> --> char* after change content: "<< buffer << endl;
printVector(vdata);
return 0;
}
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。