0

I am reading STL tutorial at following link

http://cs.brown.edu/people/jak/proglang/cpp/stltut/tut.html

How to fix compilation error?

Here following code is mentioned

#include <algorithm>
#include <vector>
#include <stdlib.h>
#include <iostream>
#include <iterator>

using namespace std;

template <class ForwardIterator, class T>
void iota_n (ForwardIterator first, int n, T value)
{
  for (int i = 0; i < n; i++) {
      *first++ = *value++;
  }
}


void main ()
{

  vector<int> v;
  iota_n (v.begin(), 100, back_inserter(v));

  random_shuffle (v.begin(), v.end());                         // shuffle
  copy (v.begin(), v.end(), ostream_iterator<int> (cout, "\n")); // print

}

While compiling facing following error.

error C2440: '=' : cannot convert from 'std::back_insert_iterator<_Container>' to 'int'

venkysmarty
  • 11,099
  • 25
  • 101
  • 184

1 Answers1

2
void iota_n (ForwardIterator first, int n, T value)

This prototype requires the iterator as the first argument, but you're passing it as the initial value instead.

When you replace the iota_n call with

iota_n (back_inserter(v), 100, 42);

and fix the assignment inside the function:

*first++ = value++;

You'll get the result you want.

krzaq
  • 16,240
  • 4
  • 46
  • 61