有时候也会遇到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());
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
- 18
- 19
- 20
- 21
- 22
- 23
- 24
- 25
- 26
- 27
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
- 18
- 19
- 20
- 21
- 22
- 23
- 24
- 25
- 26
- 27
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>
std::vector<std::string> sentence;
sentence.push_back("aa");
sentence.push_back("ab");
std::stringstream ss;
std::copy(sentence.begin(), sentence.end(),std::ostream_iterator<std::string>(ss,"\n"));
std::cout<<ss.str()<<std::endl;
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
- 18
- 19
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
- 18
- 19