使用输出迭代器不起作用的通用函数示例

a generic function example using output iterator not working

本文关键字:函数 不起作用 输出 迭代器      更新时间:2023-10-16

我有以下模板函数:

template<class In, class Out>
Out copy(In begin, In end, Out dest)
{
    while(begin != end)
        *dest++ = *begin++;
    return dest;
}

当我打电话给以下电话时:

static const double arr[] = {50,23, 56,1,78,23,25,26,143,120};
vector<double> values(arr, arr + sizeof(arr) / sizeof(arr[0]) );

// Using copy
// ----------
vector<double> values_copy;
copy(values.begin(), values.end(), back_inserter(values_copy));
for(int i=0 ; i < values_copy.size(); i++)
    cout << values_copy[i] << endl;

我收到以下编译错误(顺便说一句,g++ 开发人员,谢谢):

2-iterator.cpp: In function ‘int main()’:
2-iterator.cpp:77:63: error: call of overloaded ‘copy(std::vector<double>::iterator, std::vector<double>::iterator, std::back_insert_iterator<std::vector<double> >)’ is ambiguous
2-iterator.cpp:77:63: note: candidates are:
2-iterator.cpp:41:5: note: Out copy(In, In, Out) [with In = __gnu_cxx::__normal_iterator<double*, std::vector<double> >, Out = std::back_insert_iterator<std::vector<double> >]
/usr/include/c++/4.6/bits/stl_algobase.h:444:5: note: _OI std::copy(_II, _II, _OI) [with _II = __gnu_cxx::__normal_iterator<double*, std::vector<double> >, _OI = std::back_insert_iterator<std::vector<double> >]
[Finished in 0.7s with exit code 1]

删除:

using namespace std;
并使用 std::

cout、std::endl 等。已经有std::copy功能。