如何将一个字符串的向量引入一个字符串(优雅的方式) [英] How to implode a vector of strings into a string (the elegant way)
本文介绍了如何将一个字符串的向量引入一个字符串(优雅的方式)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我在寻找最优雅的方式来将一个字符串的向量引入一个字符串。下面是我现在使用的解决方案:
static std :: string& implode(const std :: vector< std :: string>& elems,char delim,std :: string& s)
{
for(std :: vector< std :: string& const_iterator ii = elems.begin(); ii!= elems.end(); ++ ii)
{
s + =(* ii);
if(ii + 1!= elems.end()){
s + = delim;
}
}
return s;
}
static std :: string implode(const std :: vector< std :: string>& elems,char delim)
{
std :: string s;
return implode(elems,delim,s);
}
有没有其他人吗?
<这可能不是很明显,但在
implode
中添加字符串时,你正在做大量的内存分配和释放。一个可能的改进是 reserve()
为 s
一次,然后所有的添加。 I'm looking for the most elegant way to implode a vector of strings into a string. Below is the solution I'm using now:
static std::string& implode(const std::vector<std::string>& elems, char delim, std::string& s)
{
for (std::vector<std::string>::const_iterator ii = elems.begin(); ii != elems.end(); ++ii)
{
s += (*ii);
if ( ii + 1 != elems.end() ) {
s += delim;
}
}
return s;
}
static std::string implode(const std::vector<std::string>& elems, char delim)
{
std::string s;
return implode(elems, delim, s);
}
Is there any others out there?
解决方案
It might not be obvious but while adding strings in implode
you are doing lots of memory allocations and deallocations. A possible improvement is to do reserve()
for s
once and the then all your additions.
这篇关于如何将一个字符串的向量引入一个字符串(优雅的方式)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文