通常使用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; }郑重声明:本文版权归原作者所有,转载文章仅为传播更多信息之目的,如作者信息标记有误,请第一时间联系我们修改或删除,多谢。