如何从std :: vector中创建std :: string< string> ;? [英] How to construct a std::string from a std::vector<string>?
本文介绍了如何从std :: vector中创建std :: string< string> ;?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我想从 std :: vector< std :: string> $ c $构建
std :: string
c>。
I'd like to build a std::string
from a std::vector<std::string>
.
我可以使用 std :: stringsteam
,但想象有一个更短的方法:
I could use std::stringsteam
, but imagine there is a shorter way:
std::string string_from_vector(const std::vector<std::string> &pieces) {
std::stringstream ss;
for(std::vector<std::string>::const_iterator itr = pieces.begin();
itr != pieces.end();
++itr) {
ss << *itr;
}
return ss.str();
}
我还可以如何做呢?
推荐答案
您可以使用
标准函数为< numeric>
标题中的std :: accumulate() string
s定义
You could use the std::accumulate()
standard function from the <numeric>
header (it works because an overload of operator +
is defined for string
s which returns the concatenation of its two arguments):
#include <vector>
#include <string>
#include <numeric>
#include <iostream>
int main()
{
std::vector<std::string> v{"Hello, ", " Cruel ", "World!"};
std::string s;
s = accumulate(begin(v), end(v), s);
std::cout << s; // Will print "Hello, Cruel World!"
}
或者,您可以使用更有效的小 for
cycle:
Alternatively, you could use a more efficient, small for
cycle:
#include <vector>
#include <string>
#include <iostream>
int main()
{
std::vector<std::string> v{"Hello, ", "Cruel ", "World!"};
std::string result;
for (auto const& s : v) { result += s; }
std::cout << s; // Will print "Hello, Cruel World!"
}
这篇关于如何从std :: vector中创建std :: string< string> ;?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文