字符串C ++中的乘法 [英] string Multiplication in C++
问题描述
这里已经有一个问题:如何在C ++中重复字符串可变次数?因为问题配制不当主要是关于字符乘法的答案。有两个正确,但昂贵的答案,所以我将在这里提高要求。
There is already a question for this here: How to repeat a string a variable number of times in C++? However because the question was poorly formulated primarily answers about character multiplication were given. There are two correct, but expensive answers, so I'll be sharpening the requirement here.
Perl提供 x
运算符: http://perldoc.perl .org / perlop.html#Multiplicative-Operators ,让我这样做:
Perl provides the x
operator: http://perldoc.perl.org/perlop.html#Multiplicative-Operators which would let me do this:
$foo = "0, " x $bar;
我知道我可以使用辅助函数,例如另一个答案中的函数。我想知道我可以做没有我自己的帮助功能吗?我的首选项将是一个,我可以初始化一个 const字符串
与,但如果我不能这样做,我很确定这可以用标准算法回答,一个lambda。
I understand that I can do this with the helper functions such as those in the other answer. I want to know can I do this without my own helper function? My preference would be something that I could initialize a const string
with, but if I can't do that I'm pretty sure that this could be answered with a standard algorithm and a lambda.
推荐答案
您可以覆盖乘法运算符
#include <string>
#include <sstream>
#include <iostream>
std::string operator*(const std::string& str, size_t times)
{
std::stringstream stream;
for (size_t i = 0; i < times; i++) stream << str;
return stream.str();
}
int main() {
std::string s = "Hello World!";
size_t times = 5;
std::string repeated = s * times;
std::cout << repeated << std::endl;
return 0;
}
...或使用lambda ...
... or use a lambda ...
#include <string>
#include <sstream>
#include <iostream>
int main() {
std::string s = "Hello World!";
size_t times = 5;
std::string repeated = [](const std::string& str, size_t times) {std::stringstream stream; for (size_t i = 0; i < times; i++) stream << str; return stream.str(); } (s, times);
std::cout << repeated << std::endl;
return 0;
}
...或者使用引用捕获的lambda ...
... or use a lambda with reference capturing ...
#include <string>
#include <sstream>
#include <iostream>
int main() {
std::string s = "Hello World!";
size_t times = 5;
std::string repeated = [&s, ×]() {std::stringstream stream; for (size_t i = 0; i < times; i++) stream << str; return stream.str(); }();
std::cout << repeated << std::endl;
return 0;
}
c $ c> std :: string 结合使用 std :: string
:reserve(size_t),因为你已经知道(或可以计算)结果字符串的大小。
Instead of using std::stringstream
you could also use std::string
in combination with std::string::reserve(size_t)
as you already know (or can calculate) the size of the result string.
std::string repeated; repeated.reserve(str.size() * times);
for (size_t i = 0; i < times; i++) repeated.append(str);
return repeated;
这可能更快:比较 http://goo.gl/92hH9M 与 http://goo.gl/zkgK4T
这篇关于字符串C ++中的乘法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!