本书中的示例副本:
#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>)
任何人都可以帮我纠正它,为什么?
答案 0 :(得分:2)
看起来像是函数声明中的拼写错误。第二个参数(last
)应该是input_iterator_tag
而不是output_iterator_tag
,因为它应与first
迭代器匹配,因为它直接与first
进行比较。< / p>
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)
注意:它适用于您的第一个案例的原因是输入和输出类型都相同。