如何高效输出两个交替字符或无需循环
How can two alternating characters be output efficiently or without a loop?
解释
这个问题有点棘手,但假设必须显示两个交替的字符:
for(int n=0; n<20; n++)
{
cout<<(n%2==0 ? 'X' : 'Y');
}
是否有单行或更有效的方法来完成上述任务?(即使用类似<iomanip>
setfill()
的东西)?
我想我会保持简单:
static const char s[] ="XY";
for (int n=0; n<20; n++)
std::cout << s[n&1];
另一个明显的可能性是一次只写出两个字符:
for (int n=0; n<total_length/2; n++)
std::cout << "XY";
如果我处理字符串和简洁的代码比性能更重要(就像你在 Python 中所做的那样),那么我可能会写这个:
static const std::string pattern = "XY";
std::cout << pattern * n; //repeat pattern n times!
为了支持这一点,我会在我的字符串库中添加这个功能:
std::string operator * (std::string const & s, size_t n)
{
std::string result;
while(n--) result += s;
return result;
}
一个你有这个功能,你也可以在其他地方使用它:
std::cout << std::string("foo") * 100; //repeat "foo" 100 times!
如果你有用户定义的字符串文字,比如_s
,那么就写这个:
std::cout << "foo"_s * 15; //too concise!!
std::cout << "XY"_s * n; //you can use this in your case!
在线演示。
很酷,不是吗?
如果 n
有合理的上限,您可以使用:
static const std::string xy = "XYXYXYXYXYXYXYXYXYXYXYXYXYXYXYXYXYXYXYXY";
cout << xy.substr( 0, n );
或者,为了安全起见,您可以添加:
static std::string xy = "XYXYXYXYXYXYXYXYXYXYXYXYXYXYXYXYXYXYXYXY";
while( xy.size() < n ) xy += "XYXYXYXYXYXYXYXYXYXYXYXYXYXYXYXYXYXYXYXY";
cout << xy.substr( 0, n );
最后,考虑cout.write( xy.c_str(), n );
效率是否对您最重要,以避免substr()
复制结果的开销。
相关文章: