1

I've been looking around in, and coding some basic examples for std::algorithm and for some reason i never found it odd that they work like this for example:

#include <vector>
#include <algorithm>
int main(){
  std::vector<int> vec;
  vec.resize( 100 );

  std::generate( std::begin( vec ), std::end( vec ), std::rand );   
  auto element = std::max_element( std::begin( vec ), std::end( vec ) );
}

How come it does not require template parameters like this:

std::generate<std::vector<int>::iterator>( ... 
std::max_element<std::vector<int>::iterator>( ...
Edgar Rokjān
  • 17,245
  • 4
  • 40
  • 67
val
  • 729
  • 6
  • 19
  • 1
    your title already has the answer... `std::being(vec)` is a `std::vector::iterator`, so no need to tell it to the compiler again – 463035818_is_not_an_ai Jun 22 '17 at 11:31
  • 1
    I'm not sure what you are asking. Are you asking why you don't need to explicitly define an iterator for generate() and max_element? std::begin and std::end return iterators and the type of the vector is included in vec. – quinz Jun 22 '17 at 11:31

2 Answers2

3

Look at std::generate possible implementation:

template<class ForwardIt, class Generator>
void generate(ForwardIt first, ForwardIt last, Generator g)
{
    while (first != last) {
        *first++ = g();
    }
}

Here ForwardIt type is deduced by the compiler from first and last parameters.

Then, both std::begin and std::end functions return iterators for the container. These are std::vector iterators in your case.

Consequently, ForwardIt is deduced as a type of std::vector iterator and you do not have to specify it explicitly.

The same logic applies to other algorithms.

Zlatomir
  • 6,964
  • 3
  • 26
  • 32
Edgar Rokjān
  • 17,245
  • 4
  • 40
  • 67
  • Edited the post to correct a small issue and i just want to add that _template argument deduction_ is the key word if op want to search more on this subject. – Zlatomir Jun 22 '17 at 11:54
  • @Zlatomir thanks for providing the answer with a better wording) – Edgar Rokjān Jun 22 '17 at 11:55
2

std::begin and std::end return iterators so you don't need to tell it explicitly to the compiler. Also as you are passing the vector as a parameter to those two functions, the compiler will know the template parameter.

quinz
  • 1,282
  • 4
  • 21
  • 33