[英]Why is the return type of std::reverse_iterator::operator[] unspecified?
[英]how to use std::<list>::reverse_iterator with operator +?
我嘗試了這個:
#include <iterator>
#include <list>
int main()
{
std::list<int> list(200);
std::list<int>::reverse_iterator it = list.rbegin() + 100;
}
在編譯時,它抱怨:
error: no operator "-" matches these operands
operand types are: const std::_List_iterator<int> - std::ptrdiff_t
balabalabalabalabalabalabalabalabalabalabalabala...
我在std::vector
上嘗試了相同的代碼,效果很好。 我的問題是如何將std::<list>::reverse_iterator
與operator +
?
std::list
沒有隨機訪問迭代器。 這意味着您不能隨意增加它們。 您可以使用任一++
運算符來增加它們:
std::list<int>::reverse_iterator it = list.rbegin()++;
要么
std::list<int>::reverse_iterator it = ++(list.rbegin());
您也可以使用std::advance
或std::next
來執行多個步驟,但是在內部,它們將一步一步地執行。 遍歷列表是O(N)操作。
例如,
std::list<int>::reverse_iterator it = std::next(list.rbegin(), 100);
要么
std::list<int>::reverse_iterator it = list.rbegin();
std::advance(it, 100);
在這兩種情況下, ++
將被應用100次。 因此,如果您需要經常執行此操作,則最好使用std::vector
而不是std::list
,因為std::vector
這些操作為O(1)。 實際上,您應該有很充分的理由在vector
上使用選擇list
。 這很少是一個好選擇。
std::list
具有雙向迭代器。 沒有為雙向迭代器定義operator +
。 它僅為隨機訪問迭代器定義,例如std::vector
迭代器。 對於雙向迭代器,必須使用標准函數std::next
和std::prev
,而雙向迭代器又需要使用operator ++
或operator --
對於迭代器需要次數。
例如你可以寫
std::list<int>::reverse_iterator it = std::next( list.rbegin(), 100 );
前提是該列表包含許多元素。
函數std::next
和std::prev
在標頭<iterator>
中聲明
替代函數是標准函數std::advance
。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.