最有效的可能的代码打印一个特定的板c++
Most efficient possible code for printing a specific board C++
所以我试图打印一个板完全像这样的多维数组
char score[10][10] = {' '};
a b c d e f g h i j
+-------------------+
0| |
1| |
2| |
3| |
4| |
5| |
6| |
7| |
8| |
9| |
+-------------------+
目前这是我的代码:
#include <iostream>
using namespace std;
#include <vector>
#include <string.h>
int main() {
char score[10][10] = {' '};
cout << " a b c d e f g h i j" << endl;
cout << " +-------------------+" << endl;
for (int i = 0; i < 10; i++) {
cout << " " << i << "|";
for (int j = 0; j < 10; j++) {
cout << score[i][j];
}
if(i == 0) {
cout << " |";
} else {
cout << " |";
}
cout << endl;
}
cout << " +-------------------+" << endl;
}
如你所见,我的代码既低效又冗长。什么将是最有效的可能的方式(或更有效的方式)打印板正如上面所示的多维分数数组?
正如注释所指出的,您的代码几乎是尽可能高效的。使它更短对它的运行时间没有什么作用,反而模糊了它的含义。然而,你可以做一些事情来加快速度。
-
避免对
operator<<
的额外调用,std::end
的求值,以及通过使用n
并将其包含在现有的字符串字面量中(在编译时求值)来避免不必要的缓冲区刷新。 -
使用
printf
代替cout
。参见本文的"性能"部分。
正如其他人已经指出的那样,没有很多方法可以使其更有效,特别是在限制使用cout
流的情况下。
但是对于"冗长"部分,这是短了几行和几个字符,尽管c++ 11:
cout << " a b c d e f g h i jn"
" +-------------------+n";
for (int i = 0; i < 10; i++) {
cout << ' ' << i << '|';
for (char s : score[i])
cout << s;
cout << " |n";
}
cout << " +-------------------+n";
我不明白为什么空格应该打印在最后,而不是很好地对齐内部的列,但我按照你在你的代码中所做的。
我也摆脱了不必要的endl
,它触发流刷新并将单个字母字符串更改为字符常量,但我对由此产生的效率增益有点怀疑。毕竟,它只是打印一些输出,而不是时间紧迫的计算任务。
我假设当你说你想让高效和不冗长时,你真正的意思是你想让正确和可读 。
我不相信你现在拥有的是"正确的"。我假设char score[10][10]
将包含一个单独的可打印字符的每一个正方形的板,也许是一个空字符的单元格,你不想打印任何东西。您希望将score
的内容打印到所示的模板中。按照目前的情况,如果你在char score[10][10]
中放入一个空格以外的任何东西,你就会把你的模板搞砸。
至于可读性,我认为你目前拥有的是合理的可读性,也许它会受益于一些函数提取有意义的名字,但这只是我个人的偏好。根据我对你试图做的事情的假设,这里是我的更正和重构版本:
#include <iostream>
#include <vector>
#include <string>
void printHeader() {
std::cout << " a b c d e f g h i jn";
std::cout << " +-------------------+n";
}
void printFooter() {
std::cout << " +-------------------+n";
}
void printRowStart(int i) {
std::cout << " " << i << "|";
}
void printRowEnd() {
std::cout << "|n";
}
void printSquare(char score) {
char printable_score = (score != ' ') ? score : ' ';
std::cout << printable_score;
}
void printRowScore(char (&row_score)[10]) {
printSquare(row_score[0]);
for (int i = 1; i != 10; ++i) {
std::cout << " ";
printSquare(row_score[i]);
}
}
void printScore(char (&score)[10][10]) {
printHeader();
for (int i = 0; i != 10; ++i) {
printRowStart(i);
printRowScore(score[i]);
printRowEnd();
}
printFooter();
}
int main(){
char score[10][10] = { { 0 } };
// Added to test assumed usage
score[4][5] = 'x';
score[4][6] = 'x';
printScore(score);
}
您可能还想考虑将代码打印为通用的ostream
,以使其更易于测试。
- 如何创建一个CMake变量,除非显式重写,否则使用默认值
- 删除一个线程上有数百万个字符串的大型哈希映射会影响另一个线程的性能
- 为什么两个不同的未命名名称空间可以共存于一个cpp文件中
- 运行同一解决方案的另一个项目的项目
- 挂起和取消挂起一个文件DLL
- 用C++中的一个变量定义一个常量
- 函数向量_指针有不同的原型,我可以构建一个吗
- 在c++中用vector填充一个简单的动态数组
- 如何在选项卡视图Qt中设置一个新项目,并保存以前的项目
- 预处理器:插入结构名称中的前一个行号
- 我在c++代码中生成了一个运行时#3异常
- 我想将一个对T类型的非常量左值引用绑定到一个T类型的临时值
- 从链接列表c++中删除一个项目
- 告诉一个 const char 数组,除了编译时 C 样式的字符串外,它不以 '