gpt4 book ai didi

c++ - “Essential C++” ch3.9用"back_inserter(ivec2)"替换"ivec2.begin()"编译不了

转载 作者:行者123 更新时间:2023-11-28 02:26:11 25 4
gpt4 key购买 nike

这本书的示例拷贝:

#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++ - “Essential C++” ch3.9用"back_inserter(ivec2)"替换"ivec2.begin()"编译不了,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30586649/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com