您好,登录后才能下订单哦!
密码登录
登录注册
点击 登录注册 即表示同意《亿速云用户服务条款》
通常使用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进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。