[英]Copy constructor for a generic doubly-linked list
template <class T>
class list
{
public:
//stuff
list(const list &cctorList); //cctor
private:
struct node
{
node *next;
node *previous;
T *info;
}
node *firstNode; //pointer to the first node (NULL if none)
node *lastNode; //pointer to the last node (NULL if none)
}
我現在正在嘗試定義list(const list &cctorList); //cctor
list(const list &cctorList); //cctor
但是我遇到了麻煩。
這是我到目前為止所擁有的:
template <class T>
list<T>::list(const list &cctorList)
{
node *another = new node;
firstNode = another;
another->previous = NULL;
another->info = new T(*(cctorList->info));
// ...
}
一切都達到了這一點嗎? 有沒有辦法讓我遞歸分配another->next
? 另外,使用迭代器是否有更簡單的方法來實現這一目的?
你應該使用std::list
。 實際上,你應該使用std::vector
,因為它對於大多數實際用途來說更快(如果對象真的很大或構造起來非常昂貴,列表只會更快)並且你不需要隨機訪問。
new T(*(cctorList->info));
不會編譯,因為cctorList
( list&
)沒有operator->
而且它也沒有info
成員。
復制構造函數最好根據其他更原始的操作(如push_back
和iteration)實現。 所以首先要做的就是復制構造函數變成:
template <class T> list<T>::list(const list &cctorList) { std::copy(begin(cctorList), end(cctorList), std::back_inserter(this)); }
實際上我只是模板構造函數:
template <class T, class Collection> list(const Collection &cctorList)
(身體保持不變)。 這可以作為復制構造函數,但也允許從任何可以隱式轉換為T的類型的任何其他集合進行復制。
實際數據應按值保存 。 即node
應定義為
struct node { node *next; node *previous; T info; }
無論如何,您正在復制該值,因此您不需要為node
和T
執行兩次單獨的分配。
編輯:你說你想學習概念。 但現代C ++最重要的概念是算法組合。 他們的定義通常是微不足道的。 std::copy
基本實現只是:
template <typename InputIterator, typename OutputIterator>
OutputIterator copy(InputIterator begin, InputIterator end, OutputIterator out) {
for(;begin != end; ++out, ++begin) *out = *begin;
}
現在這似乎沒有分配任何東西。 訣竅在於back_insertion_iterator
。 插入迭代器是一種技巧,可以在不預先分配序列的情況下完成這項工作。 它使用底層集合上的push_back
定義operator*
並忽略operator++
。 這滿足了“輸出迭代器”的概念,因為它只保證在這兩個調用被嚴格交錯時工作,並使算法可以處理從普通舊數組到輸出流的許多事情。
另一部分是,雖然平凡的定義是正確的,但它們不是庫中使用的實際定義。 庫中的實際定義已經過優化。 例如,通常std::copy
將檢查輸入迭代器是否知道它們的距離以及輸出是否為插入運算符以使用reserve
操作進行排序並調用它以避免某些分配。 這些是優化並依賴於標准庫的實現細節。
您可以從標准庫中記下事物的基本實現,如果您想了解它們,則測試它們的工作原理是相同的。 但是你應該遵循標准庫定義的方式,通過簡單的幫助位來構建它們,比如std::copy
, std::swap
,insert iterator adapter等。 如果您查看標准庫,大多數功能都是單行!
編輯2:同樣具有標准庫提供的所有通用性,仍有一些批評因為不夠通用。 例如GotW#84:Monoliths“Unstrung”討論了std::string
哪些方法可以轉換為通用算法。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.