How to retrieve value type from iterator in C++?
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 - b开发者_如何学JAVAegin)/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
?
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.
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
The answer of Steve is right; in C++98, you have to use std::iterator_traits or you can use Iter::value_type if you know that the iterator has this typedef (e.g. is derived from std::iterator). However, there is another problem in your code: you normally can't simply divide iterators. This works with pointers, of course, but not in the more general case. A more general approach would be:
Iter itPivot = std::advance(begin, std::distance(begin, end)/2);
精彩评论