Reputation: 73
Is there any way to make this run faster and still do the same thing?
#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++ || OS: Windows
Upvotes: 6
Views: 2708
Reputation: 27201
As Marc B said in the comments, putting the output into a string first should be faster:
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;
}
Upvotes: 4
Reputation: 17114
The obvious solution is to declare the box
array differently:
char box[20][81];
Then you can cout
a row at a time. If you can't do this for whatever reason, then there's no need to use std::string here -- a char
array is faster:
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?
}
Upvotes: 2