簡體   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