15

I was looking into <algorithm>'s fill and fill_n function, and to me they seem to do about the same thing but are just defined differently.

Is this true, and if not, how are they different?

The wording for their descriptions seem to be about the same (that I read from MSDN at fill_n and fill).

If they are the same, what is the advantage of having both of these functions available?

It is to just give a developer more options, or is one faster than the other?

paxdiablo
  • 854,327
  • 234
  • 1,573
  • 1,953
mmurphy
  • 1,327
  • 4
  • 15
  • 30

1 Answers1

36

They're not the same function, no. std::fill fills a range, given a start and end iterator. std::fill_n fills a certain number of elements, given a start iterator and a quantity. fill_n is useful for output iterators, when there's no way for you to get an end iterator, such as with std::ostream_iterator:

std::fill( std::ostream_iterator<int>(std::cout), ???, x);
                                                  ^^^
                                           what do I put here?

std::fill_n( std::ostream_iterator<int>(std::cout), 25, x);
Benjamin Lindley
  • 101,917
  • 9
  • 204
  • 274