向量的back_inserter错误

时间:2017-11-22 13:41:02

标签: c++ stl

我正在阅读以下链接中的STL教程

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

如何解决编译错误?

下面提到以下代码

#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

}

编译时遇到以下错误。

错误C2440:&#39; =&#39; :无法转换为&#39; std :: back_insert_iterator&lt; _Container&gt;&#39;到&#39; int&#39;

1 个答案:

答案 0 :(得分:2)

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

这个原型需要迭代器作为第一个参数,但你将它作为初始值传递。

替换iota_n来电时
iota_n (back_inserter(v), 100, 42);

并修复函数内的赋值:

*first++ = value++;

你会得到你想要的结果。