[英]Splitting Doubly linked list C++
我想知道我為什么會得到錯誤:為什么terminating with uncaught exception of type std::out_of_range: coordinates (400,0) outside valid range of [0, 399] X [0, 239]
我運行以下代碼。
該方法假定在傳遞給它的索引處分割DLL。 因此split(2)
會留下它被2個節點調用的列表,而舊列表的其余部分將作為新列表返回。 我嘗試了許多不同的方式來編寫此代碼,但它們都沒有起作用(必須使用unique_ptrs進行分配)。
template <class T>
auto dl_list<T>::split(node* start, unsigned split_point)
-> std::unique_ptr<node>
{
assert(split_point > 0);
if(start == nullptr)
return nullptr;
node* curr = start;
uint64_t i = 0;
while(i < split_point)
{
curr = (curr->next).get();
i++;
}
std::unique_ptr<node> temp{nullptr};
temp = std::move(curr->prev->next);
(temp)->prev = nullptr;
return temp;
}
這是包裝方法,如果有幫助的話:
template <class T>
auto dl_list<T>::split(unsigned split_point) -> dl_list
{
if (split_point >= size_)
return {};
if (split_point == 0)
{
dl_list lst;
swap(*this);
return lst;
}
auto old_size = size_;
auto new_head = split(head_.get(), split_point);
// set up current list
size_ = split_point;
for (tail_ = head_.get(); tail_->next; tail_ = tail_->next.get())
;
// set up returned list
dl_list ret;
ret.head_ = std::move(new_head);
for (ret.tail_ = ret.head_.get(); ret.tail_->next;
ret.tail_ = ret.tail_->next.get())
;
ret.size_ = old_size - split_point;
return ret;
}
假設始終存在上一個節點(即帶有標頭節點的列表),則以下代碼可取消鏈接指定節點和列表的其余部分,位於該節點的左側(prev)一側:
auto unlinked_list_from( Node* p )
-> Node*
{
p->prev->next = nullptr;
p->prev = nullptr;
return p;
}
查找第n個節點是一個單獨的問題。
在找到第n個節點並將其與列表的其余部分解除鏈接時,將兩者結合起來是一個較高級別的問題,在其中使用了兩個較低級別的解決方案。
對於鏈接列表或樹的內部指針中的std::unique_ptr
或std::shared_ptr
類的用戶所有權智能指針,通常不是一個好主意 。 從負責破壞的意義上講,每個節點都不擁有上一個和下一個節點。 這是原始指針統治的一種情況。
但是,除了學習和高級編程外,請使用標准庫容器,例如std::vector
。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.