std:vector<char> 和std:string相互转换(vector to stringstream)
最后更新于:2022-04-01 06:41:40
##实战c++中的string系列--std:vector<char> 和std:string相互转换(vector to stringstream)
有时候也会遇到std:vector与转std:string 相互转换的情况。
首先看一下`vector<char>`如何转string:
~~~
std::vector<char> *data = response->getResponseData();
std::string res;
//方法一
for (int i = 0;i<data->size();++i) {
res+=(*data)[i];
}
res+='\0';
std:cout << res;
//方法二
std::vector<char> *data = response->getResponseData();
std::string res;
res.insert(res.begin(), data->begin(), data->end());
std::cout << res;
//方法三
std::vector<char> *data = response->getResponseData();
std::string res;
const char* s = &(*data->begin());
res = std::string(s, data->size());
std::cout << res;
//方法四
string ch = "what a fucking day!";
vector <char> ta;
ta.resize(ch.size());
ta.assign(ch.begin(),ch.end());
~~~
string 转vector就会更容易:
~~~
vector <char> ta = {‘a’, 'b', 'c'};
ch.clear();
ch.assign(ta.begin(),ta.end());
~~~
================================================================
**vector to stringstream**
~~~
#include <iostream>
#include <sstream>
#include <vector>
#include <string>
#include <iterator>
// Dummy std::vector of strings
std::vector<std::string> sentence;
sentence.push_back("aa");
sentence.push_back("ab");
// Required std::stringstream object
std::stringstream ss;
// Populate
std::copy(sentence.begin(), sentence.end(),std::ostream_iterator<std::string>(ss,"\n"));
// Display
std::cout<<ss.str()<<std::endl;
~~~