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
?
What you want is to access the contents of the container at the position designated by the iterator. You can access the contents at position it using *it . Similarly, you can call methods on the contents at position it (if the contents are an object) using it->method() .
Iterator type can be checked by using typeid.
There are various kinds of iterators: input, output, forward, bidirectional, and random-access. Each has a different specification, and although random-access is a strict superset of the bidirectional interface, they are totally unrelated in the C++ type system.
You could pass a const reference, but usually iterators are small enough that it gives no advantage over passing by value.
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 was 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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With