Home > Net >  Implementation of std::vector<T>::iterator::operator[]
Implementation of std::vector<T>::iterator::operator[]

Time:11-21

For this code:

  std::vector<int> vec{0, 1, 2, 3, 4, 5, 6, 7};
  std::cout << (vec.begin()   4)[2] << " \n"; // prints out 6
  std::cout << (vec.begin()   4)[-1] << "\n"; // prints out 3

It output 6 and 3 as expected.

I checked the cppreference, but couldn't find the definition of std::vector::iterator::operator[], so I am wondering if is this actually defined behavior.

I checked the header file vector and follows it to bits/stl_vector.h and the iterator definition at bits/stl_iterator.h. My compiler version is g -11 (Ubuntu 11.1.0-1ubuntu1~20.04) 11.1.0

It is clear that in bits/stl_iterator.h an iterator's element (_M_current) is a T* (see the iterator's typedef in bits/stl_vector.h). So negative index as pointer arithmetic makes sense. But is it defined, that the type iterator must imitate a T*, such that all arithmetic operations of a random access iterator must be compatible with a pointer?

Also, is T*::operator[] defined in C ? Where can I find its definition?

CodePudding user response:

std::vector<T>::iterator is a Cpp17RandomAccessIterator, where for an iterator a, a[n] works as *(a n).

And "T*::operator[]" is called the "built-in subscript operator" which, when selected, means pointer[index] is identical to *((pointer) (index)). It is defined here, satisfying the requirement for Cpp17RandomAccessIterator immediately.

For the purposes of overload resolution, it has the signature T& operator[](T*, std::ptrdiff_t) (Though the index isn't actually converted to std::ptrdiff_t). This is a built-in declaration, so will be somewhere in the compiler itself.

  • Related