簡體   English   中英

如何優化此代碼以此格式打印?

[英]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;
}
  • 只有一個List遍歷
  • for-loop而不是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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM