How to retrieve value type from iterator in C++?

Starting from C++20 you can also use the following (together with an example):

#include <iostream>
#include <vector>

template<typename Iter>
void quickSort(Iter begin, Iter end)
{
    using T = std::iter_value_t<Iter>;
    //..
    T pivot = * ( begin + (end - begin)/2 );
    std::cout << "Element: " << pivot << std::endl;
    //..
}

int main(int argc, char* argv[]){
  std::vector<int> vec = {0,1,2,3,4,5};
  quickSort<std::vector<int>::iterator>(vec.begin(), vec.end());
  return 0;
}

output:

Element: 3

This will also work starting c++ 11:

typename Iter::value_type

So you do not have to type the whole std::iterator_traits thing.


typename std::iterator_traits<Iter>::value_type

This will work if your template is instantiated with Iter as a pointer type.

By the way, typename isn't part of the type itself. It tells the compiler that value_type really is a type. If it were the name of a function or a static data member, then that affects the syntax. The compiler doesn't necessarily know what it is, since the specialization of iterator_traits for Iter might not be visible when the template is compiled.

Tags:

C++

Iterator