简体   繁体   中英

What does operator++ do on a forward iterator

From my understand, std::unordered_map and std::unordered_set use forward iterators.

I could do something like this

auto it = unordered_map_instance.begin(); 
it++; 

But I can't do something like this

auto it = unordered_map_instance.begin(); 
it = it + 1; 

I've always thought ++ is simply just incrementing by 1, but that doesn't appear to be so with forward iterators. Could someone explain what ++ does for forward iterators? I can't seem to google this operator. +

If you refer to[iterator.requirements] from the C++ standard, iterator requires the operator++() (and operator++(int) for most types) to be overloaded. These are not to be confused with operator+(int) , which would be the equivalent of your second example. The ++ operator is not the same as addition.

As to what the operator++() actually does, is it simply moves ahead by one in the list, ie to the next element. For example:

std::map<int,int> map_instance = { { 1,1 }, {2,2}, {3,3} };
auto it = map_instance.begin(); // it points to {1,1}
it++;  // now it points to {2,2}

Incrementing by more than one can be done with std::advance

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM