c++ - 我如何优化此代码以这种格式打印?

标签 c++ performance c++11 optimization time-complexity

我想打印这样一个链表:

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;
}
  • 只遍历一次List
  • for 循环而不是 while。
  • 速度并不重要,因为您的列表应该很小(除非您有非常非常宽的屏幕或非常小的字体),因为您希望列表的内容能够整齐地适合输出窗口的 1 行。<

关于c++ - 我如何优化此代码以这种格式打印?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35714754/

相关文章:

c++ - clang 提示 constexpr 函数以防 switch 语句

c++ - g++、位域和 ADL

c++ - 如果跨线程共享变量,将变量标记为 volatile 有用吗?

javascript - 局部变量与参数

c++ - std::function 作为类的友元

c++ - 如何使我的 std::vector 实现更快?

c++ - 使用两个参数初始化 STL vector

c++ std 正则表达式为什么不匹配?

PHP:不区分大小写的参数

java - 如何从 Java 中的未排序数组中快速获取前 N 个出现项?