“基本C++” ch3.9使用 “back_inserter(ivec2)” 取代 “ivec2.begin()” 不能编译
这个例子从书中复制:“基本C++” ch3.9使用 “back_inserter(ivec2)” 取代 “ivec2.begin()” 不能编译
#include "stdafx.h" #include<functional>
#include<iostream>
#include <vector>
#include <algorithm>
#include<iterator>
using namespace std;
template<typename input_iterator_tag, typename output_iterator_tag,
typename elem_type, typename comp>
output_iterator_tag
filter(input_iterator_tag first, output_iterator_tag last,
output_iterator_tag at, const elem_type &val, comp pred)
{
while ((first = find_if(first, last, bind2nd(pred, val))) != last)
{
cout << "found value: " << *first << endl;
*at++ = *first++;
}
return at;
}
int _tmain(int argc, _TCHAR* argv[])
{
const int elem_size = 8;
int ia[elem_size] = { 12, 8, 43, 0, 6, 21, 3, 7 };
vector<int>ivec(ia, ia + elem_size);
int ia2[elem_size];
vector<int>ivec2(elem_size);
cout << "filtering integer array for values less than 8\n";
filter(ia, ia + elem_size, ia2, elem_size, less<int>());
cout << "filtering integer vector for value greater than 8\n";
filter(ivec.begin(), ivec.end(), ivec2.begin(), elem_size, greater<int> ());//it's work ok
filter(ivec.begin(), ivec.end(), back_inserter(ivec2), elem_size, greater<int>());//compile error,no instance of function template "filter" matches
system("pause");
return 0;
}
我为什么用“back_inserter( ivec2)“取代”ivec2.begin()“,但它不能在visual studio中编译;
IntelliSense: no instance of function template "filter" matches the argument list argument types are: (std::_Vector_iterator<std::_Vector_val<std::_Simple_types<int>>>, std::_Vector_iterator<std::_Vector_val<std::_Simple_types<int>>>, std::back_insert_iterator<std::vector<int, std::allocator<int>>>, const int, std::greater<int>)
任何人都可以帮我纠正它,为什么?
回答:
看起来像函数声明中的拼写错误。第二个参数(last
)应该是input_iterator_tag
而不是output_iterator_tag
,因为它应该与first
迭代器相匹配,因为它将直接与first
进行比较。
template<typename input_iterator_tag, typename output_iterator_tag, typename elem_type, typename comp>
output_iterator_tag
filter(input_iterator_tag first, input_iterator_tag last,
output_iterator_tag at, const elem_type &val, comp pred)
注意:它为您的第一个案例工作的原因是,输入和输出类型都是相同的。
以上是 “基本C++” ch3.9使用 “back_inserter(ivec2)” 取代 “ivec2.begin()” 不能编译 的全部内容, 来源链接: utcz.com/qa/263666.html