vector 与char *

通常使用vector来存储二进制数据(比如网络数据包).因此它会与char* 进行相互转换,具体方法如下例所示:

#include 
#include 
#include 
#include 
#include 

using namespace std;

void printVector(const vector& v){
    cout << "vector content         : ";
    for_each(v.cbegin(), v.cend(), [](const char& val)->void{cout << val; });
    cout << endl;
}

int main() {

    vector 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* : "<< out << endl;
    out[0] = 'j';//can changes the vector's content
    cout <<"vector --> char* after change content: "<< out << endl;
    printVector(vdata);

    cout << endl;
    cout <<"get copied char* from vector..."< --> char* : "<< buffer << endl;
    buffer[0] = 'z';//can changes the vector's content
    cout << "vector --> char* after change content: "<< buffer << endl;
    printVector(vdata);

    return 0;
}

转载于:https://blog.51cto.com/xwandrew/2049292

你可能感兴趣的:(vector 与char *)