Why are lines 7 and 8 bad?? Why it's bad to in-/decrement some iterator?
#include <unordered_map>
int main()
{
std::unordered_multimap<int,int> myumm({{1,3},{3,2},{5,5},{0,9}});
auto first = myumm.begin();
auto second = first+1; // bad
auto third = --myumm.end(); // bad too
auto fourth = myumm.end();
}
std::unordered_multimap
offers Forward Iterators. These are iterators which you can assign, dereference, compare, and increment.
To be able to decrement an iterator ( --it
), you need at least a Bidirectional Iterator (such as offered by std::multimap
).
To be able to add (an arbitrary number) to an iterator ( it + 1
), you need a Random Access Iterator (such as offered by std::vector
). To advance a weaker iterator by more than one place, use std::advance(it, 42)
(for advancing it
in place), or std::next(it, 42)
(which returns the incremented copy and does not modify it
).
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.