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

后端 未结 3 2005
甜味超标
甜味超标 2020-12-30 19:59

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

template

        
相关标签:
3条回答
  • 2020-12-30 20:06

    This will also work starting c++ 11:

    typename Iter::value_type
    

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

    0 讨论(0)
  • 2020-12-30 20:08

    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);
    
    0 讨论(0)
  • 2020-12-30 20:09

    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.

    0 讨论(0)
提交回复
热议问题