我是 C++ 的新手,我想知道有没有办法连接来自 vector< string>
的字符串使用 copy()
变成一个字符串.我知道我可以使用 accumulate()
,但我想知道这段代码“在幕后”有什么问题:
string concat_v (const vector<string>& v) {
string s;
copy(v.begin(), v.end(), back_inserter(s));
return s;
}
或者用:
s.insert(s.end(), v.begin(), v.end());
最佳答案
您的代码示例的问题在于您无法将 string
复制到需要 char
的内容。这是同样的问题:
string s = "Hello";
char ch = s; // ???
std::accumulate
函数完全符合您的要求,我不确定为什么您仍然想知道是否有办法 :) 使用它的方式是:
string s;
s = std::accumulate(v.begin(), v.end(), s);
它调用operator+
来进行累加。还有一个 accumulate 版本,它调用您提供的自定义函数。
关于c++ - 使用 copy() 连接字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27260734/