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

Viewed 18205

My question is sure a simple one for anybody familiar with C++ syntax. I'm learning C++ and this is some sort of homework.

template<typename Iter>
void quickSort(Iter begin, Iter end)
{        
    //..
    auto pivot = * ( begin + (end - begin)/2 );
    //..
}

pivot is supposed to contain the value from the center of the interval [begin, end].

The code I wrote there works, but auto is a keyword from the new C++11 language standard. How to do it the old-way? What do I write instead of auto?

4 Answers

This will also work starting c++ 11:

typename Iter::value_type

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

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
Related