aya*_*ane 5 c++ optimization char output
解释这个问题有点棘手,但假设必须显示两个交替的字符:
for(int n=0; n<20; n++)
{
cout<<(n%2==0 ? 'X' : 'Y');
}
Run Code Online (Sandbox Code Playgroud)
是否有一种单行或更有效的方法来完成上述任务?(即使用类似<iomanip>的setfill())?
我想我会保持简单:
static const char s[] ="XY";
for (int n=0; n<20; n++)
std::cout << s[n&1];
Run Code Online (Sandbox Code Playgroud)
另一个明显的可能性是一次只写出两个字符:
for (int n=0; n<total_length/2; n++)
std::cout << "XY";
Run Code Online (Sandbox Code Playgroud)
如果我使用字符串和简洁的代码比性能更重要(就像你在Python中那样),那么我可能会写这样:
static const std::string pattern = "XY";
std::cout << pattern * n; //repeat pattern n times!
Run Code Online (Sandbox Code Playgroud)
为了支持这一点,我将在我的字符串库中添加此功能:
std::string operator * (std::string const & s, size_t n)
{
std::string result;
while(n--) result += s;
return result;
}
Run Code Online (Sandbox Code Playgroud)
一个你有这个功能,你也可以在其他地方使用它:
std::cout << std::string("foo") * 100; //repeat "foo" 100 times!
Run Code Online (Sandbox Code Playgroud)
如果您有用户定义的字符串文字,比如说_s,那么只需写下:
std::cout << "foo"_s * 15; //too concise!!
std::cout << "XY"_s * n; //you can use this in your case!
Run Code Online (Sandbox Code Playgroud)
在线演示.
很酷,不是吗?