我想从std::vector<std::string>构建一个std::string。
我可以使用std::stringsteam,但想象一下有一种更短的方法:
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();
}我还能怎么做呢?
发布于 2013-03-12 03:43:59
为什么不直接使用operator +将它们相加呢?
std::string string_from_vector(const std::vector<std::string> &pieces) {
return std::accumulate(pieces.begin(), pieces.end(), std::string(""));
}默认情况下,std::accumulate在幕后使用std::plus,在C++中添加两个字符串是连接,因为std::string的运算符+是重载的。
https://stackoverflow.com/questions/15347123
复制相似问题