有時候也會遇到std:vector與轉std:string 相互轉換的情況。
首先看一下vector
如何轉string:
std::vector *data = response->getResponseData();
std::string res;
//方法一
for (int i = 0;isize();++i) {
res+=(*data)[i];
}
res+='\0';
std:cout << res;
//方法二
std::vector *data = response->getResponseData();
std::string res;
res.insert(res.begin(), data->begin(), data->end());
std::cout << res;
//方法三
std::vector *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 ta;
ta.resize(ch.size());
ta.assign(ch.begin(),ch.end());
string 轉vector就會更容易:
vector ta = {‘a’, 'b', 'c'};
ch.clear();
ch.assign(ta.begin(),ta.end());
================================================================
vector to stringstream
#include
#include
#include
#include
#include
// Dummy std::vector of strings
std::vector 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(ss,"\n"));
// Display
std::cout<