繁体   English   中英

怎样才能让cout更快?

[英]How can I make cout faster?

有没有办法让这个运行更快,仍然做同样的事情?

#include <iostream>

int box[80][20];

void drawbox()
{
    for(int y = 0; y < 20; y++)
    {
        for(int x = 0; x < 80; x++)
        {
            std::cout << char(box[x][y]);
        }
    }
}

int main(int argc, char* argv[])
{
    drawbox();
    return(0);
}

IDE:DEV C ++ || 操作系统:Windows

正如Marc B在评论中所说,首先将输出放入字符串应该更快:

int box[80][20];

void drawbox()
{
    std::string str = "";
    str.reserve(80 * 20);

    for(int y = 0; y < 20; y++)
    {
        for(int x = 0; x < 80; x++)
        {
            str += char(box[x][y]);
        }
    }

    std::cout << str << std::flush;
}

显而易见的解决方案是以不同方式声明box数组:

char box[20][81];

然后你可以一次cout一行。 如果由于某种原因你不能这样做,那么就不需要在这里使用std :: string - 一个char数组更快:

char row[81] ; row[80] = 0 ;
for (int y = 0; y < 20; y++)
  {
  for (int x = 0 ; x < 80 ; x++)
    row[x] = char(box[x][y]) ;
  std::cout << row ;
  // Don't you want a newline here?
  }

当然,从stdio.h使用putchar

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM