Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

c++

iterator

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?

like image 630
Ilya Smagin Avatar asked Oct 19 '10 11:10

Ilya Smagin


People also ask

How can I get data from iterator?

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() .

How do I find my iterator type?

Iterator type can be checked by using typeid.

What is the datatype of iterator?

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.

Are iterators passed by reference or value?

You could pass a const reference, but usually iterators are small enough that it gives no advantage over passing by value.


2 Answers

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.

like image 174
Steve Jessop Avatar answered Sep 21 '22 10:09

Steve Jessop


This will also work starting c++ 11:

typename Iter::value_type 

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

like image 32
Churianov Roman Avatar answered Sep 23 '22 10:09

Churianov Roman