我想创建一个函数,它将一个字符串和一个整数作为参数,并返回一个包含重复给定次数的字符串参数的字符串.
例如:
std::string MakeDuplicate( const std::string& str, int x )
{
...
}
Run Code Online (Sandbox Code Playgroud)
打电话MakeDuplicate( "abc", 3 );会回来"abcabcabc".
我知道我可以通过循环x次来做到这一点,但我确信必须有更好的方法.
luk*_*uke 19
我没有看到循环问题,只要确保你先保留:
std::string MakeDuplicate( const std::string& str, int x )
{
std::string newstr;
newstr.reserve(str.length()*x); // prevents multiple reallocations
// loop...
return newstr;
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
945 次 |
| 最近记录: |