簡體   English   中英

C ++,std :: list的左/右旋轉

[英]C++, left/right rotation of std::list

有沒有辦法如何使用std::rotate作為列表

std::list<int> v = { 0,7, 1,2 };

因為這些左/右旋轉

std::rotate(v.begin(), v.begin() + 1, v.end());
std::rotate(v.rbegin(), v.rbegin() + 1, v.rend());

為矢量工作?

std::vector<int> v = { 0, 7, 1, 2 };

一種可能的方法是將列表復制到向量

std::vector<int> u{ std::begin(v), std::end(v) };

反之亦然,但我發現它太“冗長”......直接輪換列表會導致以下錯誤:

Error   C2672   'std::rotate': no matching overloaded function found    
Error   C2676   binary '+':  std::_List_iterator<std::_List_val<std::_List_simple_types<_Ty>>>' does not define this operator or a conversion to a type acceptable to the predefined operator

謝謝你的幫助。

你不能添加到std::list iterator,因為它不是隨機訪問。 但你可以增加它。 那就是std::next為你做的事情:

void rot_slow( std::list<Item>& seq )
{
    std::rotate( seq.begin(), next( seq.begin() ), seq.end() );
}

但是,這個邏輯使用std::rotate ,使用O(n)交換操作。

這是不必要的低效率。 如果要旋轉列表中O(n²)復雜度的所有項目。 它很快變得很慢。

而只是拼接列表末尾的第一個項目:

void rot_fast( std::list<Item>& seq )
{
    seq.splice( seq.end(), seq, seq.begin() );
}

這使用0項交換,O(1)復雜度。

調用的唯一語法問題

 std::rotate(v.begin(), v.begin() + 1, v.end());

std::list迭代器不模擬隨機訪問迭代器而是雙向迭代器 因此,您不能向它們添加或從中減去積分值。 相反,像這樣調用std::rotate

std::rotate(v.begin(), std::next(v.begin()), v.end());
std::rotate(v.rbegin(), std::next(v.rbegin()), v.rend());

在這里, std::next增加你的迭代器,無論它滿足什么概念。 這就是為什么有時候首先使用它(在你的情況下,當使用std::vector )更好的原因,因為它增加了一個間接級別而不是someIterator + 1 ,在那里你硬連接隨機訪問要求。

暫無
暫無

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

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