1

As the title says, I know that cbegin() to an unordered_map has a constant complexity, but is the iteration of the iterator of constant complexity. e.g.: cbegin()++; cbegin() + 10; cbegin() + i; cend()--; Are all these o(1) ???

  • 3
    The iterators supplied by `std::unordered_map` are **forward iterators**. Forward iterators do not support addition: `cbegin()+10` and `cbegin()+i` are not valid. Forward iterators do not support decrement: `cend()--` is not valid. – Pete Becker Dec 25 '17 at 16:10
  • `std::unordered_map` is likely implemented as a hash table of pointers into a doubly linked list, and obviously that won't support random access iterators – Passer By Dec 26 '17 at 03:23

1 Answers1

1

24.2.1 [iterator.requirements.general]

All the categories of iterators require only those functions that are realizable for a given category in constant time (amortized). Therefore, requirement tables for the iterators do not have a complexity column.

The first part of this might be slightly confusing, but all it says is that not all iterator types support all operations (i.e., no random access with forward iterators); but those functions that are defined, they always have amortized constant complexity. The standard does not explicitly specify the complexity of each individual iterator method; it appears to indicate, in this clause, that those iterator methods that are defined must have amortized constant complexity.

Sam Varshavchik
  • 84,126
  • 5
  • 57
  • 106