如何优化此代码以这种格式打印
How can I optimize this code to print in this format?
我想打印一个这样的链表:
0 1 2 3 4
12 24 36 85 48
我当前的代码是
void LinkedList::printList()
{
curr = head; //store head in curr to irerate
int count = 0; //counter to help uer manipulate list
while (curr != NULL) //traverse whole list
{
cout << count++ <<"t"; //print index
curr = curr->next; //move to next
}
curr = head; //make current head again
cout << endl;//go to next line
while (curr != NULL) //traverse whole list
{
cout << curr->data << "t"; //print data
curr = curr->next; //move to next
}
cout << endl;
}
我很确定还有另一种方法可以做到这一点,这是一种更简单,更快捷的方法。我想减少此代码的冗余。
我正在显示计数器以帮助用户添加或删除数字。
#include <sstream>
void LinkedList::printList(std::ostream& os = std::cout) {
size_t counter = 0;
std::ostringstream indx;
std::ostringstream value;
for( ListNode *current = head; current != NULL; current = current->next ) {
indx << counter++ << "t";
value << current->data << "t";
}
os << indx.str().c_str() << std::endl << value.str().c_str() << std::endl;
}
- 只有一个列表遍历
- for 循环而不是 while。
- 速度并不重要,因为您的列表应该很小(除非您有一个非常非常宽的屏幕或很小的字体),因为您希望列表的内容整齐地适合输出窗口的 1 行。
这实际上取决于您所说的"优化"是什么意思。 链表本质上是遍历的次优选择,因为缓存局部性较差。 更不理想的是将整数数据转换为文本并写入流。
因此,我只能得出结论,您希望减少代码冗余,并将其视为优化,即使以牺牲执行时间为代价。 一种可能的解决方案是接受应用于每个元素的函数:
void LinkedList::forEach( std::function<void (node*)> fn )
{
for( node *curr = head; curr != NULL; curr = curr->next )
{
fn( curr );
}
}
现在你可以用它来打印节点数据或其他东西:
void LinkedList::printList()
{
int count = 0;
forEach( [&count]( node * ) { cout << count++ << "t"; } );
cout << endl;
forEach( []( node *n ) { cout << n->data << "t"; } );
cout << endl;
}
您可以尝试使用 ANSI 转义码来移动打印输出位置,并在一个循环中完成所有操作。http://www.tldp.org/HOWTO/Bash-Prompt-HOWTO/x361.html
相关文章:
- C++ 将打印格式从整数 2255 更改为 $xx.xx
- 在 c++ 中以十六进制格式打印无符号字符(BYTE).使用 std::cout
- C++计算未以正确的格式打印
- 注意:"Entity_c::Entity_c(const Entity_c&)"被隐式删除,因为默认定义格式不正确:
- 如何以特定格式C++打印二叉搜索树
- C++:根据int值的基数使用条件格式打印
- 使用宏定义打印格式参数
- 如何在Qt中打印.xlsx格式
- 被隐式删除,因为默认定义格式不正确:
- 使用访问器以两种格式打印数据
- 悬挂式C 打印形状来自字符串阵列
- 测试用例之间的不同打印格式
- 如何总是在一行中获得C 的一个陈述?(格式/叮当式)
- 在 c++ 中使用 setfill() 以特定格式打印十进制数
- 如何以可读格式打印控制字符
- 如何在 c++ 中的字符串中显式打印“”
- 以树格式打印堆数组
- 如何打印可流式传输类型的 boost::变体
- 使用格式字符串打印类
- 如何将格式字符串打印到窗口中