簡體   English   中英

為什么我不能增加std :: unordered_map迭代器?

[英]Why can't I increment std::unordered_map iterator?

std::unordered_map<int, int> _cache;

std::vector<std::unordered_map<int, int>::iterator> _lruList;

這很有效

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

但事實並非如此

std::rotate(_cache.begin(), _cache.begin() + 1, _cache.end()); // error occurs on _cache.begin() + 1 saying "error type"

這對我來說真的沒有意義,因為它們都是迭代器,除了一個用於vector而一個用於unordered_map

然后我也嘗試了這個std::rotate(_cache.begin(), _cache.begin() ++, _cache.end());

但我得到以下錯誤: _Left: you can't assign to a variable that is const _Right: you can't assign to a variable that is const

unordered_map迭代器是前向迭代器。 這意味着他們一次只能移動一步,只能向前移動,從一個位置移動到另一個位置需要遍歷所有中間位置。 因此,前向迭代器不支持operator+ ,因為它將是O(n)操作。 標准庫的作者認為,當人們看到a + b ,他們希望是O(1),因此如果迭代器類型不能滿足該要求,則不應該支持運算符。

vector迭代器是隨機訪問,這意味着它們支持operator+ ,因為它可以實現為O(1)。 你可以這樣做:

std::rotate(_cache.begin(), std::next(_cache.begin()), _cache.end());

除此之外也不起作用,因為std::rotate是一個修改操作。 並且您無法修改unordered_map中元素的鍵。

暫無
暫無

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

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