如何有效地输出两个交替的字符或没有循环?

时间:2013-09-21 05:39:57

标签: c++ optimization char output

解释这个问题有点棘手,但假设必须显示两个交替的字符:

for(int n=0; n<20; n++)
{
    cout<<(n%2==0 ? 'X' : 'Y');
}

是否有单线或更有效的方法来完成上述任务? (即使用类似<iomanip>的{​​{1}})?

3 个答案:

答案 0 :(得分:7)

我想我会保持简单:

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";

答案 1 :(得分:6)

如果我使用字符串和简洁代码比性能更重要(就像你在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!

Online demo

很酷,不是吗?

答案 2 :(得分:2)

如果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()复制结果的开销。