练习 9.41:编写程序,从一个vector<char>初始化一个string。
首先给一个网上的答案:
#include <iostream>
#include <string>
#include <vector>
using std::cout;
using std::endl;
using std::string;
using std::vector;
int main()
{
vector<char> c = {'h', 'e', 'l', 'l', 'o', '!'};
string s(c.begin(), c.end());
cout << s << endl;
return 0;
}
但个人觉得不符合习题所在章节试图传授的知识,切合题意的答案应该是使用string s(cp, n)的形式:
#include <iostream>
#include <string>
#include <vector>
using std::cout;
using std::endl;
using std::string;
using std::vector;
int main()
{
vector<char> c = {'h', 'e', 'l', 'l', 'o', '!'};
string s(&c[0], c.size());
cout << s << endl;
return 0;
}